'方
法:工程 - 引用-Microsoft WinHTTP Services, version 5.1
'说
明:WinHttp可以伪造HTTP协议头,伪装成真正的浏览器来访问网页,从而得到更真实的数据,比XmlHTTP相比更加灵活一些(一般用XmlHTTP不行的话,WinHttp决对能搞定)
'注
意:每个网站的协议头都不一样,这得看抓包数据结果来决定该设置哪些协议头,有些网站不能加"User-Agent"这个文件头,否则不会返回结果
Private Sub Command1_Click() '模拟GET
Dim WinHttp As WinHttp.WinHttpRequest '声明一个对象
Set WinHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
WinHttp.Open "GET", "http://www.baidu.com/", True
WinHttp.SetTimeouts 30000, 30000, 30000, 30000 '设置超时时间
WinHttp.Option(WinHttpRequestOption_SslErrorIgnoreFlags) = &H3300 '忽略错误
'------------------------------------------------------------------------
WinHttp.SetRequestHeader "Accept-Language", "zh-cn"
WinHttp.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
'------------------------------------------------------------------------设置文件头(具体协议头该设置啥这得看抓包结果)
WinHttp.Send
'发送
WinHttp.WaitForResponse '异步发送
While WinHttp.Status <> 200
DoEvents
Wend
Text1.Text = BytesToBstr(WinHttp.ResponseBody, "UTF-8")
'返回HTML(同样可用WinHttp.ResponseText返回HTML)
Text2.Text = WinHttp.GetAllResponseHeaders
'返回所有协议头
Set WinHttp = Nothing
End Sub
Private Sub Command2_Click() '模拟POST
Dim ShuJu As String
Dim WinHttp As WinHttp.WinHttpRequest '声明一个对象
Set WinHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
ShuJu = "name=abc,pass=123456" '设置POST数据
WinHttp.Open "POST", "http://www.baidu.com/xxx", True
WinHttp.SetTimeouts 30000, 30000, 30000, 30000 '设置超时时间
WinHttp.Option(WinHttpRequestOption_SslErrorIgnoreFlags) = &H3300 '忽略错误
'------------------------------------------------------------------------
WinHttp.SetRequestHeader "Content-Length", Len(ShuJu)
WinHttp.SetRequestHeader "Accept-Language", "zh-cn"
WinHttp.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
'------------------------------------------------------------------------设置文件头(具体协议头该设置啥这得看抓包结果)
WinHttp.Send ShuJu
'发送
WinHttp.WaitForResponse
'异步发送
While WinHttp.Status <> 200
DoEvents
Wend
Text1.Text = BytesToBstr(WinHttp.ResponseBody, "UTF-8")
'返回HTML(同样可用WinHttp.ResponseText返回HTML)
Text2.Text = WinHttp.GetAllResponseHeaders
'返回所有协议头
Set WinHttp = Nothing
End Sub
Public Function BytesToBstr(strBody, CodeBase) '编码转换("UTF-8"或者"GB2312"或者"GBK")
Dim ObjStream
Set ObjStream = CreateObject("Adodb.Stream")
With ObjStream
.Type = 1
.Mode = 3
.Open
.Write strBody
.Position = 0
.Type = 2
.Charset = CodeBase
BytesToBstr = .ReadText
.Close
End With
Set ObjStream = Nothing
End Function