“基础连接已关闭:连接意外关闭”

时间:2013-06-04 22:30:00

标签: c# webclient

当我尝试获取html页面时,我收到此错误:

The underlying connection was closed: The connection was closed unexpectedly

我认为我正在使用的网站正在使用一些基于ip的保护。

WebClient single_page_client = new WebClient();
single_page_client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
string cat_page_single = single_page_client.DownloadString(the_url);

我该怎么办? 如何使用Webclient代理?

修改

如果我使用此代码,它可以工作。为什么呢?

HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(current_url);
webrequest.KeepAlive = true;
webrequest.Method = "GET";
webrequest.ContentType = "text/html";
webrequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
//webrequest.Connection = "keep-alive";
webrequest.Host = "cat.sabresonicweb.com";
webrequest.Headers.Add("Accept-Language", "en-US,en;q=0.5");
webrequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0";

HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();

Console.Write(webresponse.StatusCode);
Stream receiveStream = webresponse.GetResponseStream();


Encoding enc = System.Text.Encoding.GetEncoding(1252);//1252
StreamReader loResponseStream = new StreamReader(receiveStream, enc);

string current_page = loResponseStream.ReadToEnd();

loResponseStream.Close();
webresponse.Close();

1 个答案:

答案 0 :(得分:0)

第一个请求不使用表示结果长度的标头。它完成时关闭连接。

第二个请求使用长度标头,读取指定的字节数,然后正常关闭连接。 (在客户端控制下而不是服务器驱动的断开连接)

- 或 -

您发送的网址导致服务器出错。服务器日志或事件查看器中是否有错误?