SHARE
TWEET

SaveFileFromURL

a guest Feb 4th, 2016 110 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Sub SaveFileFromURL()
  2.    
  3.     Const Option_SSLErrorIgnoreFlags = 4
  4.     Const SslErrorFlag_Ignore_All = 13056  ' Ignore all of the above
  5.  
  6.     Dim FileNum As Long
  7.     Dim FileData() As Byte
  8.     Dim WHTTP As Object
  9.    
  10.     mainUrl = "https://webservices.youknowtheURL.com"
  11.     fileUrl = "https://webservices.youknowtheURL.com/mobile/rest/reportservice/exportReport?name=shared%2FCharlie+Book%27s2.ppr"
  12.     filePath = "C:\myfile.csv"
  13.    
  14.     myuser = "loginname"
  15.     mypass = "password"
  16.    
  17.     '@David Zemens, I got this by examining webpage code using Chrome, thanks!
  18.     strAuthenticate = "start-url=%2F&user=" & myuser & "&password=" & mypass & "&switch=Log+In"
  19.    
  20.     Set WHTTP = CreateObject("WinHTTP.WinHTTPrequest.5.1")
  21.    
  22.    
  23.     'I figured out that you have to POST authentication string to the main website address not to the direct file address
  24.     WHTTP.Open "POST", mainUrl, False 'WHTTP.Open "POST", fileUrl, False
  25.        
  26.     WHTTP.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
  27.     WHTTP.Option(Option_SSLErrorIgnoreFlags) = SslErrorFlag_Ignore_All
  28.    
  29.     On Error Resume Next
  30.     WHTTP.Send strAuthenticate
  31.     If Err.Number <> 0 Then
  32.         MsgBox Err.Number & ": " & Err.Description
  33.         Exit Sub
  34.     End If
  35.    
  36.     'Then you have to GET direct file url
  37.     WHTTP.Open "GET", fileUrl, False
  38.     WHTTP.Send
  39.    
  40.     FileData = WHTTP.ResponseBody
  41.     Set WHTTP = Nothing
  42.    
  43.     'Save the file
  44.     FileNum = FreeFile
  45.     Open filePath For Binary Access Write As #FileNum
  46.         Put #FileNum, 1, FileData
  47.     Close #FileNum
  48.    
  49.     MsgBox "File has been saved!", vbInformation, "Success"
  50.    
  51. End Sub
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top