1

我正在尝试编写一个宏来从网络上进行一些查询以更新 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技巧?

4

1 回答 1

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 会导致它失败。所以。这绝对是怎么回事。

这可能是我们出色的网络技术人员试图阻止宏病毒接触恶意网站的尝试。

于 2015-07-13T15:57:09.730 回答