我需要使用 VB.NET 应用程序中的 Web 资源。我已成功检索到访问令牌并准备使用它来调用受保护的资源。但是,每次我调用受保护的资源时,我都会收到 401 Unauthorized 响应,因为 Authorization 字段尚未添加到标头中。
这是我的代码。
WebRequest = DirectCast(Net.WebRequest.Create(ApiUri), HttpWebRequest)
WebRequest.Method = "POST"
WebRequest.ContentType = "application/json"
WebRequest.ContentLength = Bytes.Length
Dim RequestStream As IO.Stream = WebRequest.GetRequestStream
RequestStream.Write(Bytes, 0, Bytes.Length)
RequestStream.Close()
WebRequest.Headers("Authorization") = "OAuth " & _
"oauth_version=""1.0""," & _
"oauth_nonce=""" & Nonce & """," & _
"oauth_timestamp=""" & TimeStamp & """," & _
"oauth_consumer_key=""" & ConsumerKey & """," & _
"oauth_token=""" & Token & """," & _
"oauth_signature_method=""HMAC-SHA1""," & _
"oauth_signature=""" & Signature & """"
WebResponse = DirectCast(WebRequest.GetResponse(), HttpWebResponse)
然后我使用 Fiddler 监控请求。我在 Fiddler 中看到的只是带有 401 响应的请求,如下所示(不包括正文)。
要求
POST ***url*** HTTP/1.0
Content-Type: application/json
Host: ***host***
Content-Length: 45
Connection: Keep-Alive
回复
HTTP/1.0 401 Unauthorized
X-Powered-By: PHP/5.3.13
WWW-Authenticate: Basic realm="***realm***"
Content-type: application/json
Content-Length: 79
Connection: keep-alive
Date: Mon, 07 Jan 2013 01:13:22 GMT
Server: lighttpd/1.4.28
我在互联网上读到的所有地方都表明 HttpWebRequest 应该首先挑战服务器并收到 401 响应,正如我在这里看到的那样。然后它应该再次尝试将 Authorization 字段添加到标头并获得 200 OK 响应。这第二部分不会发生。我不明白这是如何正常工作的,还是我做错了什么?