3
我在查詢維基百科使用下面的代碼,但我總是得到一個錯誤(403禁止)。但是,當我在瀏覽器中輸入完全相同的網址時,它可以正常工作。我之前一直在使用相同的代碼來查詢其他web apis,所以我不確定是什麼導致了這個問題。維基百科查詢返回錯誤403
private static string query(string text)
{
text = text.Replace(" ", "%20");
string url = "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + text + "&format=json&callback=spellcheck";
WebClient client = new WebClient();
client.Headers.Add("User-Agent", "whatever"); // <-- this line was missing
try
{
string response = client.DownloadString(url);
return response;
}
catch(Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
這是用戶代理標題。 –
@spender api在頭文件中需要這些信息的目的是什麼?僅用於統計目的還是有時需要根據客戶端的用戶代理髮送不同的響應? – Pedro
http://meta.wikimedia.org/wiki/User-Agent_policy – jpatokal