【发布时间】:2019-09-10 16:49:21
【问题描述】:
如何通过在 VB.NET 中交换基本凭据(客户端 ID 和密码)(OAuth 身份验证)来请求令牌?
我尝试了下面的代码,但没有成功。我收到错误消息:
底层连接已关闭:发送时发生意外错误。
代码
Function test()
Try
Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create("https://www.ia.provider.com/access_token"), HttpWebRequest)
myHttpWebRequest.Method = "POST"
myHttpWebRequest.ContentType = "application/json"
myHttpWebRequest.Headers.Add("Authorization", "Basic " & System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("545874a9f5134ed0b54545:333650277fa4d50934c65AAb46Ad123")))
Dim myHttpWebResponse As HttpWebResponse CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
Dim myreader As New System.IO.StreamReader(myHttpWebResponse.GetResponseStream)
Dim myText As String
myText = myreader.ReadToEnd
Console.WriteLine(myText)
Catch e As ArgumentException
Console.WriteLine(e.Message)
MsgBox((vbLf & "WebException is thrown. " & vbLf & "Message is:" & e.Message))
Catch e As WebException
Console.WriteLine(vbLf & "WebException is thrown. " & vbLf & "Message is :" & e.Message)
If e.Status = WebExceptionStatus.ProtocolError Then
Console.WriteLine("Status Code: {0}", CType(e.Response, HttpWebResponse).StatusCode)
Console.WriteLine("Status Description: {0}", CType(e.Response, HttpWebResponse).StatusDescription)
Console.WriteLine("Server : {0}", CType(e.Response, HttpWebResponse).Server)
End If
Catch e As Exception
Console.WriteLine("Exception is thrown. Message is:" & e.Message)
End Try
End Function
【问题讨论】:
-
如果您在运行代码时能够更加具体和准确地了解问题所在,这将很有帮助
-
我收到错误消息:底层连接已关闭:发送时发生意外错误。
-
使用 WebRequest,一个 Https 连接,您需要明确设置 TLS1.2 协议。添加
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12。握手可能还需要ServicePointManager.ServerCertificateValidationCallback。添加一个只返回True的(除非您确实想要/需要验证服务器证书)。 -
请将完整的错误消息和堆栈跟踪添加到您的问题中,谢谢
-
现在它说:远程服务器返回错误:(500)
标签: vb.net