【问题标题】:C# - WebRequest.GetResponce(): The request was aborted: The connection was closed unexpectedlyC# - WebRequest.GetResponce():请求被中止:连接意外关闭
【发布时间】:2015-11-12 15:48:49
【问题描述】:

我遇到了这个简单代码的问题,它使用提供的 url 发送请求并从响应中读取 html。看起来它是在 ?q= 之后使用西里尔符号编码的东西,但我不明白为什么(url 实际上是从浏览器地址栏获得的,不是生成的或其他任何东西)。

url =
    "http://www.avito.ru/nizhniy_novgorod/kvartiry/sdam/na_dlitelnyy_srok?q=%D0%93%D0%B5%D0%BD%D0%B5%D1%80%D0%B0%D0%BB%D0%B0+%D0%98%D0%B2%D0%BB%D0%B8%D0%B5%D0%B2%D0%B0+10%D0%BA1";
string html = "";
try
{
    Uri uri = new Uri(url);
    WebRequest request = WebRequest.Create(uri);
    request.Timeout = 100000;

    using (WebResponse responce = request.GetResponse())
    {
        Stream stream = responce.GetResponseStream();
        StreamReader reader = new StreamReader(stream);
        html = reader.ReadToEnd();
    }
}
catch (Exception e)
{
    System.Console.WriteLine(e.Message);
}

GetResponce() 方法发生错误。消息是:

The request was aborted: The connection was closed unexpectedly.

【问题讨论】:

    标签: c# encoding webrequest


    【解决方案1】:

    您应该将您的请求和响应分别转换为 HttpWebRequest 和 HttpWebResponse。

    var url = "http://www.avito.ru/nizhniy_novgorod/kvartiry/sdam/na_dlitelnyy_srok?q=%D0%93%D0%B5%D0%BD%D0%B5%D1%80%D0%B0%D0%BB%D0%B0+%D0%98%D0%B2%D0%BB%D0%B8%D0%B5%D0%B2%D0%B0+10%D0%BA1";
            string html = "";
            try
            {
                Uri uri = new Uri(uri);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Timeout = 100000;
    
    
                using (HttpWebResponse responce = (HttpWebResponse)request.GetResponse())
                {
                    Stream stream = responce.GetResponseStream();
                    StreamReader reader = new StreamReader(stream);
                    html = reader.ReadToEnd();
                    Console.WriteLine(html);
                }
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.Message);
            }
    

    另外,http://www.avito.ru/nizhniy_novgorod/kvartiry/sdam/na_dlitelnyy_srok?q=%D0%93%D0%B5%D0%BD%D0%B5%D1%80%D0%B0%D0%BB%D0%B0+%D0%98%D0%B2%D0%BB%D0%B8%D0%B5%D0%B2%D0%B0+10%D0%BA1 的 url 似乎无效。

    使用 Fiddler,url 返回 404 错误。

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 1970-01-01
      • 2020-01-27
      • 2020-11-05
      • 1970-01-01
      • 2010-09-22
      • 2012-04-26
      • 1970-01-01
      相关资源
      最近更新 更多