vb.net 使用 HTTP 基本身份验证连接到 REST API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31384737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Connecting to REST API using HTTP Basic Authentication
提问by Adam Bradbury
I am trying to use VB.net to connect to a REST API using HTTP Basic Authentication. The authentication succeeds but subsequent requests still yield a 401 error, what am I missing?
我正在尝试使用 VB.net 连接到使用 HTTP 基本身份验证的 REST API。身份验证成功,但后续请求仍然产生401 error,我错过了什么?
Dim Client As New WebClient
Client.Credentials = New NetworkCredential("user","password")
' Works and authenticates
MsgBox(Client.DownloadString("http://site/api/login"))
' Returns 401
MsgBox(Client.DownloadString("http://site/api/helloworld"))
I should add, if I go to /api/loginand authenticate in a browser, I can then request /api/helloworldcorrectly - so the error is client side.
我应该补充一点,如果我去/api/login浏览器中进行身份验证,那么我可以/api/helloworld正确请求- 所以错误是客户端。
回答by joehanna
Try this:
尝试这个:
Dim credentials As String = Convert.ToBase64String(Encoding.ASCII.GetBytes("user" & ":" & "password"))
Client.Headers(HttpRequestHeader.Authorization) = String.Format("Basic {0}", credentials)

