我正在使用以下代码查询维基百科,但我总是收到错误(403 禁止)。但是,当我在浏览器中键入完全相同的 url 时,它可以工作。我之前一直在使用相同的代码来查询其他 web api,所以我不确定是什么导致了问题。
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;
}
}