【问题标题】:C# HttpWebRequest shows 404, but site is reachable in browserC# HttpWebRequest 显示 404,但在浏览器中可以访问站点
【发布时间】:2011-05-10 11:04:58
【问题描述】:

我正在尝试使用 c# 从网站下载 xml 文件,但在某些 url 上得到 404。这是有线的,因为它们仍然在浏览器中工作。其他网址仍然可以正常工作。

HttpWebRequest request = (HttpWebRequest)
            WebRequest.Create(url);
        request.Method = "GET";
        request.Timeout = 3000;
        request.UserAgent = "Test Client";
        HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)
                    request.GetResponse();
            }
            catch (WebException e)
            {
                response = (HttpWebResponse)e.Response;
            }
            Console.WriteLine("- "+response.StatusCode);

        XmlTextReader reader = XmlTextReader(response.GetResponseStream());

此网址是上述问题网址之一:

http://numerique.bibliotheque.toulouse.fr/cgi-bin/oaiserver?verb=ListMetadataFormats

已解决....忘记修剪 url ;)

【问题讨论】:

  • 一些服务器验证用户代理。尝试使用真实的。
  • 服务器可能正在查看 User-Agent 标头或有关请求的其他详细信息。
  • @Tom,你的代码对我来说很好用。你还有其他问题的 URI 吗?
  • @acoolaum,是的,有几个有这个问题,@evan,它也不适用于真正的 useragen
  • 这是另一个,顺便说一句,当我复制下面发布的第一行 ivo 时它起作用了,字符串前面的 @ 有什么特别之处吗? diglit.ub.uni-heidelberg.de/…

标签: c# xml httpwebrequest http-status-code-404


【解决方案1】:

我只能推测主机站点可能不喜欢您的 UserAgent 并且正在返回 404 消息

【讨论】:

    【解决方案2】:

    我用这个解决了这个问题:

    var client = (HttpWebRequest)WebRequest.Create(uri);
    client.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
    client.CookieContainer = new CookieContainer();
    client.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36";
    var htmlCodae = client.GetResponse() as HttpWebResponse;
    

    【讨论】:

      【解决方案3】:

      下载xml文件可以使用DownloadString方法:

      System.Net.WebClient client = new System.Net.WebClient();
      
      String url = "http://stackoverflow.com/feeds/question/4188449";
      
      String xmlSource = client.DownloadString(url);
      
      Console.WriteLine(xmlSource);
      

      【讨论】:

        【解决方案4】:

        也许

        1) 不知何故你输入了错误的网址:你能尝试 放

           WebRequest.Create(@"http://numerique.bibliotheque.toulouse.fr/cgi-bin/oaiserver?verb=ListMetadataFormats");
        

        而不是

          WebRequest.Create(url);
        

        用于测试目的。

        2) 你有一些 HTTP 过滤机制来区分 VS 和浏览器请求

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-10-30
          • 2021-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多