1

当我尝试获取 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();
4

1 回答 1

0

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

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

-或者-

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

于 2013-06-05T00:02:14.273 回答