本帖最后由 StartHeiMa 于 2014-7-16 18:34 编辑
网络不给力时老是卡死,怎么设置HttpWebRequest.GetResponse();超时返回呢?- class Requset
- {
- static String userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729)";
- public static String GetResponse(String url, String cookie, String refer, byte[] data = null)
- {
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- request.UserAgent = userAgent;
- request.AllowAutoRedirect = true;
- request.KeepAlive = false;
- if (data != null)
- {
- request.Method = "POST";
- request.ContentLength = data.Length;
- try
- {
- var stream = request.GetRequestStream();
- stream.Write(data, 0, data.Length);
- stream.Close();
- }
- catch { return null; }
- }
- else
- {
- request.Method = "GET";
- }
- HttpWebResponse response;
- try
- {
- response = (HttpWebResponse)request.GetResponse();
- }
- catch { return null; }
- using (var stream = response.GetResponseStream())
- {
- using (var sr = new StreamReader(stream, Encoding.UTF8))
- {
- return sr.ReadToEnd();
- }
- }
- }
- }
复制代码
|