VBA ServerXMLHTTP 代理在 https 上没问题,但在 http 上失败

VBA ServerXMLHTTP proxy is fine with https but fails on http

我正在尝试编写一个宏来从 Web 进行一些查询以更新 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=Whosebug", True))
    'This one doesn't.
    MsgBox (httpRequest("http://www.bing.com/search?q=Whosebug", True))
End Function

我确定我正在寻找正确的名称和端口,因为我已经通过 Java 测试了相同的东西,并且它满足于做两种口味(即以下一切都完美无缺代码)。

public static void main(String[] args) throws Exception {
    URL url = new URL("http://www.bing.com/search?q=Whosebug");
    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的诡计?

谜团解开了。原来这是一个围绕用户代理的安全功能(所有事情......)。

Java 使用了这些 HTTP headers(成功):

GET http://www.bing.com/search?q=Whosebug 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=Whosebug 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' user-agent 添加到 Java 导致它失败。所以。绝对是这样。

这可能是我们杰出的网络技术人员试图阻止宏病毒与恶意网站联系的尝试。