VB POST 回调函数
时间: 2023-11-18 22:52:37 浏览: 162
VB中的POST回调函数可以通过Wininet.dll库中的InternetOpen、InternetConnect、HttpOpenRequest、HttpSendRequest等函数来实现。具体步骤如下:
1. 使用InternetOpen函数初始化一个会话句柄。
2. 使用InternetConnect函数连接到服务器。
3. 使用HttpOpenRequest函数创建一个HTTP请求句柄。
4. 使用HttpSendRequest函数发送HTTP请求。
5. 使用InternetReadFile函数读取服务器返回的数据。
6. 使用InternetCloseHandle函数关闭会话句柄、连接句柄和请求句柄。
以下是一个简单的VB代码示例:
```
Private Declare Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA" (ByVal sAgent As String, ByVal lAccessType As Long, ByVal sProxyName As String, ByVal sProxyBypass As String, ByVal lFlags As Long) As Long
Private Declare Function InternetConnect Lib "wininet.dll" Alias "InternetConnectA" (ByVal hInternetSession As Long, ByVal sServerName As String, ByVal nServerPort As Integer, ByVal sUsername As String, ByVal sPassword As String, ByVal lService As Long, ByVal lFlags As Long, ByVal lContext As Long) As Long
Private Declare Function HttpOpenRequest Lib "wininet.dll" Alias "HttpOpenRequestA" (ByVal hHttpSession As Long, ByVal sVerb As String, ByVal sObjectName As String, ByVal sVersion As String, ByVal sReferer As String, ByVal lAcceptTypes As Long, ByVal lFlags As Long, ByVal lContext As Long) As Long
Private Declare Function HttpSendRequest Lib "wininet.dll" Alias "HttpSendRequestA" (ByVal hHttpRequest As Long, ByVal sHeaders As String, ByVal lHeadersLength As Long, ByVal sOptional As String, ByVal lOptionalLength As Long) As Long
Private Declare Function InternetReadFile Lib "wininet.dll" (ByVal hFile As Long, ByVal sBuffer As String, ByVal lNumBytesToRead As Long, lNumberOfBytesRead As Long) As Integer
Private Declare Function InternetCloseHandle Lib "wininet.dll" (ByVal hInet As Long) As Integer
Private Sub PostRequest()
Dim hInternetSession As Long
Dim hHttpConnection As Long
Dim hHttpRequest As Long
Dim sServerName As String
Dim sObjectName As String
Dim sPostData As String
Dim sHeaders As String
Dim lBytesWritten As Long
Dim lBytesRead As Long
Dim sResponse As String
' 初始化会话句柄
hInternetSession = InternetOpen("VB POST Request", 0, vbNullString, vbNullString, 0)
' 连接到服务器
sServerName = "www.example.com"
hHttpConnection = InternetConnect(hInternetSession, sServerName, 80, vbNullString, vbNullString, 3, 0, 0)
' 创建HTTP请求句柄
sObjectName = "/post.php"
hHttpRequest = HttpOpenRequest(hHttpConnection, "POST", sObjectName, "HTTP/1.1", vbNullString, 0, 0, 0)
' 设置POST数据和请求头
sPostData = "name=value"
sHeaders = "Content-Type: application/x-www-form-urlencoded" & vbCrLf & "Content-Length: " & Len(sPostData)
' 发送HTTP请求
HttpSendRequest hHttpRequest, sHeaders, Len(sHeaders), sPostData, Len(sPostData)
' 读取服务器返回的数据
sResponse = ""
Do
Dim sBuffer As String
sBuffer = Space(1024)
InternetReadFile hHttpRequest, sBuffer, Len(sBuffer), lBytesRead
sResponse = sResponse & Left(sBuffer, lBytesRead)
Loop While lBytesRead > 0
' 关闭句柄
InternetCloseHandle hHttpRequest
InternetCloseHandle hHttpConnection
InternetCloseHandle hInternetSession
' 输出服务器返回的数据
MsgBox sResponse
End Sub
```
阅读全文