抓取指定网页的代码时,系统调试是中断并提示:未处理的“System.Net.WebException”类型的异常出现在 system.dll 中。
其他信息: 远程服务器返回错误: (404) 未找到。
===================================
抓取网页代码:string url="http://passport.csdn.net/UserLogin.aspx";//这种网址不可能“不存在”或“拒绝访问”吧
public string readFromURL(string url)
{
  StreamReader sr;
  HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(url);
  HttpWReq.Timeout = -1;
  //HttpWReq.Method = "Get";
  //HttpWReq.KeepAlive=false;//这两句在这关系不大吧
  string str ="";
  HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
  sr = new StreamReader(HttpWResp.GetResponseStream(), System.Text.Encoding.Default"));
  HttpWResp.Close();
  str=sr.ReadToEnd();
  return str;
}

解决方案 »

  1.   

    try thishttp://singlepine.cnblogs.com/articles/292661.html
      

  2.   

    我这里并没涉及到关于POST/GET的问题啊对了,调试时是中断在:
    HttpWebResponse  HttpWResp  =  (HttpWebResponse)HttpWReq.GetResponse(); 我用本地的一个网页做测试时,中断提示是:
    未处理的“System.Net.WebException”类型的异常出现在 system.windows.forms.dll 中。
    其他信息: 请求被中止: 连接被意外关闭。
    中断在:str=sr.ReadToEnd();
      

  3.   

    上面的那段代码我是在学校(教育网)用过的,怎么回家后(中国电信ADSL)就出问题了。难道是中国电信的问题想得有点歪了
      

  4.   

    WebRequest类 也试过了,一样没用
      

  5.   

    HttpWResp.Close();
      str=sr.ReadToEnd();
    ???
    先close 还要readToEnd???
      

  6.   

    回复hdt(倦怠) :
    的确是我写错了,贴代码以前程序里已经是改过的了。问题是这样:
    当url为一级(如:http://www.a.com/index.htm)时,函数可以返回字符流,
    当url不是一级(如:http://community.a.com/b/index.htm)时,就会出现上面的问题了我通过抓包可以看到:浏览器发送的包中:
    Get /b/index.htm HTTP1.1
    Host: http://www.a.com而这个程序发送的包中仅为:
    Get http://www.a.com/b/index.htm HTTP1.1
    没有Host这一段难道是这里的问题?
    那如何用C#构造一个和浏览器生成的包一样的包呢?
    用request.Headers.Add("Host","http://www.a.com")来设置会提示标头不正确
      

  7.   

    回复hdt(倦怠) :
    在你机器上http://www.a.com/b/index.htm 这种二级地址程序也可以访问?ie问题?有什么需要注意的地方,能说一下吗?这问题难道不是由上面包的不同导致的么?
      

  8.   

    public static string getPage(String url,string referer) 
    {
    HttpWebResponse res = null;
    string strResult = ""; try 
    { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    req.Method = "GET";
    req.KeepAlive = true;
    req.Referer=referer;
    CookieContainer cookieCon = new CookieContainer();
    req.CookieContainer = cookieCon;
    req.CookieContainer.SetCookies(new Uri(url),cookieheader); res = (HttpWebResponse)req.GetResponse();
    Stream ReceiveStream = res.GetResponseStream();
    Encoding encode = System.Text.Encoding.GetEncoding("gb2312");
    //Encoding encode = System.Text.Encoding.ASCII;
    StreamReader sr = new StreamReader( ReceiveStream, encode );
    Char[] read = new Char[256];
    int count = sr.Read( read, 0, 256 );
    while (count > 0) 
    {
    String str = new String(read, 0, count);
    strResult += str;
    count = sr.Read(read, 0, 256);
    }

    catch(Exception e) 
    {
    strResult = e.ToString();

    finally 
    {
    if ( res != null ) 
    {
    res.Close();
    }
    } return strResult;
    }
    试试这个
      

  9.   

    谢谢 rungroo(狠狠地冲) 系统重装了,问题解决这可不是我希望的结果啊