.NET HttpWebRequest oAuth 401未经授权

时间:2013-01-07 02:06:06

标签: .net vb.net oauth httpwebrequest authorization

我需要从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响应,正如我在这里看到的那样。然后应该再次尝试将“授权”字段添加到标题中并获得200 OK响应。第二部分不会发生。我不明白这是如何正常工作的,还是我做错了什么?

1 个答案:

答案 0 :(得分:0)

原来你需要使用BinaryWriter而不是Stream来添加内容。

所以不要这样。

WebRequest.ContentLength = Bytes.Length
Dim RequestStream As IO.Stream = WebRequest.GetRequestStream
RequestStream.Write(Bytes, 0, Bytes.Length)
RequestStream.Close()

这样做。

Using Writer As New IO.BinaryWriter(WebRequest.GetRequestStream)
    Writer.Write(Bytes)
End Using