次のコードを使用してウィキペディアにクエリを実行していますが、常にエラーが発生します(403禁止)。ただし、ブラウザにまったく同じURLを入力すると、機能します。以前に同じコードを使用して他のWebAPIを照会したことがあるため、問題の原因がわかりません。
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;
}
}