维基百科查询返回错误403 [英] Wikipedia query returns error 403

查看:337
本文介绍了维基百科查询返回错误403的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码查询Wikipedia,但我总是收到错误(403禁止)。但是,当我在浏览器中输入完全相同的URL时,它可以正常工作。我之前一直在使用相同的代码来查询其他web apis,所以我不确定是什么原因导致了这个问题。

I'm querying Wikipedia using the following code, but I always get an error (403 forbidden). When I type the exact same url in my browser, however, it works. I've been using the same code before to query other web apis, so I am not sure what's causing the trouble.

    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; 
        }   
    }


推荐答案

尝试设置用户代理标题与您的浏览器匹配的内容。如果这不起作用,请启动 Fiddler ,查看浏览器标题并将其复制到您的网络请求。

Try setting the user agent header to something that matches your browser. If this doesn't work, fire up Fiddler, take a peek at your browser headers and copy them to your web request.

http://msdn.microsoft.com/en-us/library/system.net.webclient.headers.aspx

编辑

我给出的建议是通用的。请遵守您下载的网站的政策,因为欺骗浏览器用户代理可能违反政策或默认情况下被视为恶意:

The advice I gave was generic. Please observe the policies of the website you are downloading from, as spoofing a browser user-agent may contravene policy or be considered malicious by default:

http://meta.wikimedia.org/wiki/User-Agent_policy


不要为您的机器人复制浏览器的用户代理,因为浏览器的用户代理的类似bot的行为将被认为是恶意的。

Do not copy a browser's user agent for your bot, as bot-like behavior with a browser's user agent will be assumed malicious.

这篇关于维基百科查询返回错误403的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆