2015-07-10 90 views
1

我試圖寫一個宏來做一些查詢從網絡更新Access數據庫。出於某種原因,VBA拒絕與http友好,但完全滿足於做https。VBA ServerXMLHTTP代理與https正常,但在http上失敗

這是我的請求功能:

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

嘗試使'代理'一個變種而不是字符串 - 有時當一個變種預期一個字符串將失敗。 –

+0

或者:http://www.logikdev.com/2010/07/07/use-serverxmlhttp-through-proxy/ –

回答

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 

和訪問發送這些(這是不成功的):通過簡單地添加

xhr.setRequestHeader "User-Agent", "PayMeNoAttention" 

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 

它神奇地通過。並且爲了確認理論,將Access的用戶代理添加到Java導致它失敗。所以。這絕對是最新的。

這可能是我們輝煌的網絡技術人員試圖阻止宏病毒與惡意網站聯繫的嘗試。

相關問題