我需要从VB.NET应用程序中使用Web资源。我已成功检索到访问令牌,并准备使用它来调用受保护的资源。但是,每次我调用受保护的资源时,我都会收到一个401 Unauthorized响应,因为授权字段尚未添加到标题中。.NET HttpWebRequest oAuth 401未授权
这是我的代码。
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响应,因为我在这里看到。它应该再次尝试与授权字段添加到标题并获得200 OK响应。第二部分不会发生。我不理解这是如何正确工作的,或者我做错了什么?
考虑使用现有的oAuth库(http://oauth.net/code/)。手工操作可能会让你疯狂。 – Jason
谢谢你的回应。我已经在使用该网站的代码。我其实整个oAuth舞蹈都能正常工作。这不是问题。我不相信这个问题甚至与oAuth有关(我只是将它包括在帖子中以便完整)。我相信这个问题与HttpWebRequest相关,以及它如何与服务器进行通信。 – user1227445
您是否使用代理服务? –