我试图编写宏来从网上进行一些查询以更新Access数据库。出于某种原因,VBA拒绝与http友好,但完全满足于https。
这是我的请求功能:
Function httpRequest(ByVal url As String, useProxy As Boolean) As String
Dim response As String
Dim proxy As String
Dim xhr As Object
'Make HTTP requester object
Set xhr = CreateObject("MSXML2.ServerXMLHTTP.6.0")
If useProxy Then
If Left(url, 5) = "https" Then
proxy = "proxyb1secure:8443"
Else
proxy = "proxyb1:8080"
End If
xhr.setProxy 2, proxy
End If
xhr.Open "GET", url, False
'send the request. THIS LINE TIMES OUT ON HTTP
xhr.Send
'fetch the whole page
response = xhr.responseText
'clean up
Set xhr = Nothing
'return
httpRequest = response
End Function
我的测试功能:
Function testProxy()
'This one works
MsgBox (httpRequest("https://www.bing.com/search?q=stackoverflow", True))
'This one doesn't.
MsgBox (httpRequest("http://www.bing.com/search?q=stackoverflow", True))
End Function
我确定我正在寻找正确的名称和端口,因为我已经通过Java测试了同样的东西,并且它的内容是两种口味(即一切正常)完美地在下面的代码中。)
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.bing.com/search?q=stackoverflow");
HttpURLConnection con = (HttpURLConnection) url.openConnection(getProxyForURL(url));
System.out.println(con.getResponseCode() + " " + con.getResponseMessage());
InputStream is = con.getInputStream();
int c;
StringBuilder sb = new StringBuilder();
while ((c = is.read()) != -1) {
sb.append((char) c);
}
String page = sb.toString();
System.out.println(page);
}
public static Proxy getProxyForURL(URL url) {
if (url.getProtocol().equals("https")) {
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyb1secure", 8443));
} else {
return new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyb1", 8080));
}
}
我错过了什么样的VBA技巧?
答案 0 :(得分:1)
神秘解决了。事实证明,这是一个围绕用户代理(所有事情......)的安全功能。
Java使用了这些HTTP头(成功):
GET http://www.bing.com/search?q=stackoverflow HTTP/1.1
Accept: */*
Accept-Language: en-us
Proxy-Connection: Keep-Alive
User-Agent: Java/1.7.0_79
Host: www.bing.com
和Access发送了这些(不成功):
GET http://www.bing.com/search?q=stackoverflow HTTP/1.1
Accept: */*
Accept-Language: en-us
User-Agent: Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5)
Proxy-Connection: Keep-Alive
Host: www.bing.com
只需添加
即可xhr.setRequestHeader "User-Agent", "PayMeNoAttention"
它神奇地经历了。为了证实这一理论,将Access的用户代理添加到Java会导致它失败。所以。这肯定是什么了。
这可能是我们出色的网络技术人员阻止宏病毒与恶意网站联系的尝试。