不少网站为了提高加载速度,启用HTTP服务器的GZIP压缩功能,当客户端发送的HTTP请求中声明可以接受GZIP编码时,服务器自动对HTTP响应内容进行GZIP压缩。但是,在VBS中想自动对GZIP编码进行解压就没有那么容易了。

不同组件对GZIP压缩的处理不尽相同,首先看Msxml2.XMLHTTP:

'By Demon
'http://demon.tw
Dim http
Set http = CreateObject("Msxml2.XMLHTTP")
http.open "GET", "https://www.baidu.com", False
http.setRequestHeader "Accept-Encoding", "gzip"
http.send
WScript.Echo http.responseText

从测试的结果看,Msxml2.XMLHTTP会自动进行GZIP解压,GOOD!

其次是Msxml2.ServerXMLHTTP:

'By Demon
Dim http
Set http = CreateObject("Msxml2.ServerXMLHTTP")
http.open "GET", "https://www.baidu.com", False
http.setRequestHeader "Accept-Encoding", "gzip"
http.send
WScript.Echo http.responseText

很可惜,返回的是乱码。再看看WinHttp.WinHttpRequest.5.1:

'By Demon
Dim http
Set http = CreateObject("WinHttp.WinHttpRequest.5.1")
http.open "GET", "https://www.baidu.com", False
http.setRequestHeader "Accept-Encoding", "gzip"
http.send
WScript.Echo http.responseText

依然是乱码。虽然说一般情况下用Msxml2.XMLHTTP组件已经绰绰有余了,但是有些时候还是不行的,比如不能发送Cookie,不能伪造Referer等等。所以还是得想办法对GZIP进行解码,办法无外乎两种,自己用VBS写算法或者调用第三方组件。

算法我就偷懒不写了,感觉效率不会太高,哪位朋友感兴趣可以写来玩玩。找了个不错的第三方组件(居然用第三方,我果然老了)Chilkat.Gzip:

Dim Gzip
Set Gzip = CreateObject("Chilkat.Gzip")
Gzip.UnlockComponent ""
'By Demon
Dim http
Set http = CreateObject("WinHttp.WinHttpRequest.5.1")
http.open "GET", "https://www.baidu.com", False
http.setRequestHeader "Accept-Encoding", "gzip"
http.send
WScript.Echo Gzip.UncompressString(http.responseBody, "utf-8")

顺便说一下这个组件是收费的,可以免费试用30天,所以还是应该用VBS来实现?

原文:http://demon.tw/programming/vbs-http-gzip.html

点赞(126)

评论列表共有 0 条评论

立即
投稿
返回
顶部