VB中如何发送POST请求?
时间: 2024-09-29 12:12:47 浏览: 50
在VB.NET中发送POST请求通常通过`System.Net.WebClient`类或者更现代的`HttpClient`来完成。这里是一个使用`WebClient`的基本示例,它包含了创建表单数据并发送到服务器的过程[^1]:
```vb.net
Imports System.Net
' 创建WebClient实例
Dim client As New WebClient()
' 要发送的数据
Dim postData As String = "key1=value1&key2=value2" ' 替换为你实际的表单参数
' 设置POST方法
client.Method = WebRequestMethods.Http.Post
' 指定URL和数据
Dim url As String = "http://targetserver.com/endpoint" ' 目标服务器地址
Dim bytes As Byte() = Encoding.UTF8.GetBytes(postData)
Dim request As HttpWebRequest = DirectCast(client.OpenRead(url), HttpWebRequest)
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = bytes.Length
Using stream As Stream = request.GetRequestStream()
stream.Write(bytes, 0, bytes.Length)
End Using
' 发送请求并接收响应
Dim response As String = client.DownloadString(url)
' 处理返回的结果
Console.WriteLine(response)
' 关闭连接
client.Dispose()
```
阅读全文