1

Hi guys I have this sub I want to download a file from URL but everytime when I run it WinHttpReq.Status contains 406.

Sub DownloadFile()
    Dim myURL As String
    myURL = "https://YourWebSite.com/?your_query_parameters"

    Dim WinHttpReq As Object
    Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
    WinHttpReq.Open "GET", myURL, False, "username", "password"
    WinHttpReq.send

    myURL = WinHttpReq.responseBody
    If WinHttpReq.Status = 200 Then
        Set oStream = CreateObject("ADODB.Stream")
        oStream.Open
        oStream.Type = 1
        oStream.Write WinHttpReq.responseBody
        oStream.SaveToFile "C:\file.csv", 2 ' 1 = no overwrite, 2 = overwrite
        oStream.Close
    End If
End Sub
Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
hyunah
  • 21
  • 6

1 Answers1

0

The 406 status code means that, although the server understood and processed the request, the response is of a form the client cannot understand. A client sends, as part of a request, headers indicating what types of data it can use, and a 406 error is returned when the response is of a type not in that list.

Eg. If you ask the server to send a GIF picture, but it can only send plain text and PNG pictures you will receive a 406 status code meaning your server understood your question but cannot fulfill it.

So you should include an Accept header specifying which type of media you want your server to send to your client (your VBA), and that type should be a type that your server can actually deliver.

Example how to send headers:

WinHttpReq.SetRequestHeader "Content-Type", "text/xml;charset=utf-8"
WinHttpReq.SetRequestHeader "Accept", "text/xml" 

Of course nobody can tell you which media type is the correct because we don't know your server and which type of media it can provide.

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73