2014-09-24 173 views
0

我目前正試圖從下面詳細介紹的網站URL使用VBA中的XMLHTTP檢索json字符串。加載第一個url創建一個會話,我從HTML主體中檢索。使用開發工具中可見的會話ID &其他請求標頭調用第二個url會導致403錯誤。我已經嘗試了多種頭部組合,但沒有任何效果。爲了部署,需要一個VBA解決方案。任何輸入/想法將不勝感激。VBA XMLHTTP查詢返回403錯誤

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

XMLHttp對象不允許不安全頭設置,包括欺騙參照標頭。詳細信息請參見answer

由於請求中缺少引用程序標題,因此會返回狀態403。如果您需要從VBA獲取JSON,則需要使用Internet Explorer對象並瀏覽到first URL,一旦加載,需要通過編程方式模擬點擊正確的鏈接導航到Second URL,然後嘗試捕獲數據。