部分代码:
public string  GetSource(string http) 
{HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(http);
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
Stream resStream = HttpWResp.GetResponseStream(); 
StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
string tempCode= sr.ReadToEnd();
resStream.Close(); 
sr.Close();
return tempCode;
}
如果我一次请求HttpWebRequest达到一定的数目:200次,就会报请求超时。
for(int i=0;i<200;i++)
{
 string temp=GetSource("www.sina.com?temp="+i+"");
}
请问在哪里设置 避免  报请求超时

解决方案 »

  1.   

    HttpWebRequest是可以设置Timeout的HttpWReq.Timeout,或者用WebClient试试看/// <summary>
    /// 抓取页面接口 - WebClient
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    private string getWebContent( string contenturl ) 

    string str = "";
    contenturl = contenturl.Replace("&amp;","&");
    WebClient client = new WebClient();
    client.Headers.Add("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
    client.Headers.Add("Accept-Language","zh-cn");
    client.Headers.Add("UA-CPU","x86");
    client.Headers.Add("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
    try
    {
    byte[] buffer = client.DownloadData( contenturl ); 
    if(Form1.encoding == "utf-8")
    {
    str = System.Text.Encoding.GetEncoding("utf-8").GetString( buffer, 0, buffer.Length ); 
    }
    else
    {
    str = System.Text.Encoding.GetEncoding("gb2312").GetString( buffer, 0, buffer.Length ); 
    }
    }
    catch(Exception ex)
    {
    //MessageBox.Show(ex.Message);
    } return str;
    }