Search code examples
htmljsonexcelvbatimeout

(Excel VBA): Accessing JSON file - operation timed out


I'm attempting to pull data from a JSON file on the web. I'm using a dummy JSON file for the time being to get things working. My code is below, but it times out every time and doesn't return anything. The same happens if I use different URLs also.

Sub Test()
    Dim strResult As String
    Dim objHTTP As Object
    Dim URL As String
    Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    URL = "https://jsonplaceholder.typicode.com/posts/2"
    objHTTP.Open "GET", URL, False
    objHTTP.Send
    strResult = objHTTP.ResponseText
    MsgBox strResult
End Sub

In case it's relevant, I have the following libraries enabled in the file:

  • Visual Basic for Applications

  • Microsoft Excel 15.0 Object Library

  • OLE Automation

  • Microsoft Scripting Runtime

  • Microsoft WinHTTP Services, version 5.1

What am I missing?

EDIT: Fixed. I wasn't aware of the distinction between WinHttpRequest and XMLHTTPRequest. When using the latter, the code worked fine. Thanks all.


Solution

  • Is there a special reason why using WinHttpRequest instead of XMLHTTPRequest?

    While using WinHttpRequest the operating system defaults for HTTP requests - proxy settings for example - are not used and must be set explicitly:

    Sub Test()
        Dim strResult As String
        Dim objHTTP As Object
        Dim URL As String
        Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
        objHTTP.SetProxy 2, "proxyIP:proxyPort"
        URL = "https://jsonplaceholder.typicode.com/posts/2"
        objHTTP.Open "GET", URL, False
        objHTTP.setCredentials "username", "password", 1
        objHTTP.Send
        strResult = objHTTP.ResponseText
        MsgBox strResult
    End Sub
    

    The 2 in IWinHttpRequest::SetProxy method is HTTPREQUEST_PROXYSETTING_PROXY. The 1 in IWinHttpRequest::SetCredentials method is HTTPREQUEST_SETCREDENTIALS_FOR_PROXY.

    While using XMLHTTPRequest the operating system defaults for HTTP requests are used as set in Internet Options in control panel. So the following should run if you are able accessing the URL via browser:

    Sub Test()
        Dim strResult As String
        Dim objHTTP As Object
        Dim URL As String
        Set objHTTP = CreateObject("MSXML2.XMLHTTP.6.0")
        URL = "https://jsonplaceholder.typicode.com/posts/2"
        objHTTP.Open "GET", URL, False
        objHTTP.Send
        strResult = objHTTP.ResponseText
        MsgBox strResult
    End Sub