且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

VBA从Internet WinHttpReq下载文件,登录不起作用

更新时间:2023-10-17 17:32:28

由于alex和Kyle的提示,我查阅了这两篇解决了我问题的文章.

Thanks to alex and Kyle's hints I looked up to these 2 posts which solved my problem.

nb->没有cookie处理,并且http POST的Fiddlr正文副本请求我执行2个必需的步骤

nb -> no cookie handling and Fiddlr body copy of the http POST request the 2 required steps for me

这是我的解决方案:

Sub eds()

Dim strCookie As String, strResponse As String, _
  strUrl As String
  Dim xobj As Object
  Dim WinHttpReq As Object
  Set xobj = New WinHttp.WinHttpRequest

  UN = "2myusername"
  PW = "mypass"

  strUrl = "http://my.website.com/"
  xobj.Open "POST", strUrl, False 
  xobj.SetRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"
  xobj.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
  xobj.Send "username=" & UN & "&password=" & PW & "&login=login" 
  strResponse = xobj.ResponseText

  strUrl = http://my.website.com/date=09-10-1945%&search 'the url pointing to the CSV file
  xobj.Open "GET", strUrl, False

  xobj.SetRequestHeader "Connection", "keep-alive"
  xobj.SetRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"
  xobj.Send

  strCookie = xobj.GetResponseHeader("Set-Cookie")
  strResponse = xobj.ResponseBody

 If xobj.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write xobj.ResponseBody
    oStream.SaveToFile "C:\Users\me\Desktop\ciao\file.csv", 1
    oStream.Close
End If
End Sub