C# - WebRequest.GetResponce():请求已中止:连接意外关闭

时间:2015-11-12 15:48:50

标签: c# encoding webrequest

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

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.

1 个答案:

答案 0 :(得分:0)

您应该分别将您的请求和响应转发给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无效。

使用Fiddler,url会返回404错误。