2017-07-16 78 views
0

我試圖發送一個GET請求來下載的http://footlocker.com/ HTML內容:奇403錯誤使用Web客戶端

Console.WriteLine(new WebClient().DownloadString("http://footlocker.com")); 

但我得到一個403錯誤。爲了測試,我使用Python,試圖發送一個GET請求(請求庫),我成功地獲得了200響應以及HTML內容:

r = requests.get('http://footlocker.com') 
print(r.text) 

要看到差距,我印在Python頭要求,這就是我的了:

{'User-Agent': 'python-requests/2.13.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} 

於是,我就派與Python的Web客戶端請求需要用戶代理字符串:

WebClient wc = new WebClient(); 
wc.Headers[HttpRequestHeader.UserAgent] = "python-requests/2.13.0"; 
Console.WriteLine(wc.DownloadString("http://footlocker.com")); 

但我仍然有403什麼可能Python的請求庫和WebClient之間的區別?我在這裏錯過了很明顯的東西嗎這是爲什麼發生?

+0

如果問題出在頭也許這將幫助'wc.Headers.Add(「用戶 - 代理:python-requests/2.13.0「);',基本上你可以嘗試複製Python輸入的頭文件 – thunderbird

+0

它給出了一個錯誤:'指定的值具有無效的HTTP頭字符。'所以我將它改爲'wc .Headers.Add(「User-Agent」,「python-requests/2.13.0」);'我得到了一個403. – RaghavJhavar

回答

1

想通了,要加這個頭需要:

wc.Headers.Add("Accept", "*/*"); 

最終代碼:

WebClient wc = new WebClient(); 
wc.Headers.Add("User-Agent", "python-requests/2.13.0"); 
wc.Headers.Add("Accept", "*/*"); 
Console.WriteLine(wc.DownloadString("http://footlocker.com")); 
+0

它窩如果你使用[HttpClient]會更好(https://stackoverflow.com/questions/20530152/need-help-deciding-between-httpclient-and-webclient) – Givi