【问题标题】:C# Webclient returning error 404C# Webclient 返回错误 404
【发布时间】:2017-12-11 19:06:51
【问题描述】:

我正在使用以下脚本从 URL 中检索 HTML。

string webURL = @"https://nl.wiktionary.org/wiki/" + word.ToLower();
                using (WebClient client = new WebClient())
                {
                      string htmlCode = client.DownloadString(webURL);                
                }

变量词可以是任何词。如果没有检索到“单词”的 WIKI 页面,则代码以错误代码 404 结尾,而使用浏览器检索 URL 时会打开一个 WIKI 页面,表示该项目还没有页面。

我想要的是代码始终获取 HTML,当 WIKI 页面显示还没有信息时也是如此。我不想通过 try and catch 来避免错误 404。

有人知道为什么这不适用于 Web 客户端吗?

【问题讨论】:

  • 有点离题但是:为什么不用HttpClient 而不是WebClient
  • 我猜你必须添加client.Headers

标签: c# html http-status-code-404 webclient


【解决方案1】:

试试这个。您可以在 try catch 块中捕获 404 错误内容。

        var word = Console.ReadLine();
        string webURL = @"https://nl.wiktionary.org/wiki/" + word.ToLower();
        using (WebClient client = new WebClient() {  })
        {
            try
            {

                string htmlCode = client.DownloadString(webURL);

            }
            catch (WebException exception)
            {
                string responseText=string.Empty;

                var responseStream = exception.Response?.GetResponseStream();

                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        responseText = reader.ReadToEnd();
                    }
                }

                Console.WriteLine(responseText);
            }
        }

        Console.ReadLine();

【讨论】:

  • 请注意,WebException.Response 默认限制为 64 kB。如果需要阅读更多内容,需要设置HttpWebRequest.DefaultMaximumErrorResponseLength。 (感谢stackoverflow.com/a/43842761/72809)
【解决方案2】:

由于此 WIKI 服务器使用区分大小写的 url 映射,所以不要修改 URL 的大小写以获取(从您的代码中删除“.ToLower()”)。

例如: 小写:
https://nl.wiktionary.org/wiki/categorie:onderwerpen_in_het_nynorsk
结果:HTTP 404(未找到)

正常(未修改)情况:
https://nl.wiktionary.org/wiki/Categorie:Onderwerpen_in_het_Nynorsk
结果:HTTP 200(正常)

另外,请记住大多数(如果不是全部)WiKi 服务器(包括这个)生成自定义 404 页面,因此在浏览器中它们看起来像“普通”页面,但尽管如此,它们使用 404 http 代码提供服务。

【讨论】:

  • 感谢 Pavel,看来我最终还是得使用“try/cach”。
猜你喜欢
  • 1970-01-01
  • 2012-10-26
  • 1970-01-01
  • 2014-01-26
  • 1970-01-01
  • 2015-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多