给别人定制软件时遇到的一个问题,使用HttpWebRequest请求类时,提示错误。
这个应该是HTTPS证书的问题。
以下是解决方法。
代码如下:
'使用TLS12安全协议连接
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
'创建HTTP请求对象,并指定URL地址
Dim request As HttpWebRequest = WebRequest.Create(TextBox2.Text)
'设置HTTP请求方法为POST
request.Method = "POST"
'设置HTTP User-Agent头信息
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.100"
'不保持连接状态
request.KeepAlive = False
'设置HTTP协议版本为1.0
request.ProtocolVersion = HttpVersion.Version10
'获取POST数据并转换为字节数组格式
Dim postData As String = TextBox3.Text
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
'设置HTTP请求Content-Type头信息
request.ContentType = "application/x-www-form-urlencoded"
'设置HTTP请求Content-Length头信息
request.ContentLength = byteArray.Length
'获取HTTP请求流,在流中写入POST数据
Using dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
End Using
'发送HTTP请求并等待响应,读取响应数据并进行解析
Dim responseString As String
Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
If response.StatusCode = HttpStatusCode.OK Then
'读取响应流中的数据
Using streamReader As New StreamReader(response.GetResponseStream())
responseString = streamReader.ReadToEnd()
'将响应字符串显示在文本框4中
TextBox4.Text = responseString
'解析响应数据
解析数据(responseString)
End Using
Else
'如果返回的状态码不是200则在文本框4中显示错误信息
responseString = "Error: " & response.StatusCode.ToString()
End If
End Using
这样就可以请求成功了。不再报错。