VBA XMLHTTP查询返回403错误

时间:2014-09-24 19:08:00

标签: json vba xmlhttprequest

我目前正在尝试使用下面详述的网站网址在VBA中使用XMLHTTP检索json字符串。加载第一个URL会创建一个会话,我从HTML正文中检索该会话。使用会话ID&拨打第二个网址的电话从开发工具可见的其他请求标头会导致403错误。我尝试过多种标题组合而没有效果。出于部署目的,需要VBA解决方案。任何意见/想法都会非常感激。

Sub test()

Dim wbk_TB As Workbook
Dim var_array As Variant

Dim url As String
Dim data As Variant
Dim XMLHTTP As MSXML2.XMLHTTP
Dim hdoc As MSHTML.HTMLDocument

Set wbk_TB = ThisWorkbook
Set XMLHTTP = New MSXML2.XMLHTTP
url = "http://www.eex-transparency.com/homepage/power/germany/production/availability/non-usability"
XMLHTTP.Open "GET", url, False

XMLHTTP.setRequestHeader "Accept", "application/json, text/plain, */*"
XMLHTTP.send

data = XMLHTTP.responseText

Dim HTMLdoc As MSHTML.HTMLDocument
Set HTMLdoc = New MSHTML.HTMLDocument
HTMLdoc.body.innerHTML = XMLHTTP.responseText

Name = "session=" & HTMLdoc.getElementsByName("session").Item(0).Value

url = "http://www.eex-transparency.com/dsp/tem-12?country=de&limit=50&offset=50"

XMLHTTP.Open "GET", url, True
XMLHTTP.setRequestHeader "Host", "www.eex-transparency.com"
XMLHTTP.setRequestHeader "Proxy-Connection", "keep-alive"
XMLHTTP.setRequestHeader "Accept", "application/json, text/plain, */*"
XMLHTTP.setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"
XMLHTTP.setRequestHeader "Referer", "http://www.eex-transparency.com/homepage/power/germany/production/availability/non-usability"
XMLHTTP.setRequestHeader "Accept-Encoding", "gzip,deflate,sdch"
XMLHTTP.setRequestHeader "Cache-Control", "max-age=0"
XMLHTTP.setRequestHeader "Accept-Language", "en-US,en;q=0.8"
XMLHTTP.setRequestHeader "Cookie", Name

XMLHTTP.send

While XMLHTTP.readyState <> 4
    DoEvents
Wend

data = XMLHTTP.responseText

End Sub

1 个答案:

答案 0 :(得分:1)

XMLHttp对象不允许包含欺骗引用标头的不安全标头设置。详情请参阅此answer

由于请求中缺少referer标头,因此返回状态403。如果您需要从VBA获取JSON,则需要使用Internet Explorer对象并浏览到first URL,一旦加载,需要以编程方式模拟单击导航到Second URL在正确的链接上,然后尝试捕获数据。