GET方式的HTTP请求,返回响应体
public static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; /// <summary> /// GET方式的HTTP请求 /// </summary> /// <param name="targetUri"></param> /// <param name="timeout">超时时间</param> /// <param name="cookie">随同HTTP请求发送的Cookie信息</param> /// <returns></returns> public static HttpWebRequest CreateGetHttpWebRequest(string targetUri, int timeout = 0, CookieCollection cookie = null) { HttpWebRequest request = WebRequest.Create(targetUri) as HttpWebRequest; request.UserAgent = DefaultUserAgent; request.Method = "GET"; if (timeout != 0) request.Timeout = timeout; if (cookie != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookie); } return request; } /// <summary> /// 读取http响应信息,并返回响应体 /// </summary> /// <param name="response">HttpWebResponse对象</param> /// <returns></returns> public static string ReaderFromHttp(HttpWebResponse response) { Stream stream = null; StreamReader streamReader = null; try { var contentEncoding = response.ContentEncoding; stream = response.GetResponseStream(); if (contentEncoding == "gzip") { /*压缩数据,要进行处理*/ throw new NotImplementedException("gzip压缩数据处理还么实现"); } else { streamReader = new StreamReader(stream, Encoding.UTF8); return streamReader.ReadToEnd(); } } catch (Exception e) { return null; } finally { if (streamReader != null) { streamReader.Close(); streamReader = null; } if (stream != null) { stream.Close(); stream = null; } } } /// <summary> /// GET方式的HTTP请求,返回响应体 /// </summary> /// <param name="targetUri"></param> /// <param name="timeout">超时时间</param> /// <param name="cookie">随同HTTP请求发送的Cookie信息</param> /// <returns></returns> public static string ReturnFromGetHttp(string targetUri, int timeout = 0, CookieCollection cookie = null) { HttpWebRequest request = null; HttpWebResponse response = null; try { request = CreateGetHttpWebRequest(targetUri, timeout, cookie); response = request.GetResponse() as HttpWebResponse; return ReaderFromHttp(response); } catch (Exception e) { return null; } finally { if (response != null) { response.Close(); response = null; } if (request != null) { request.Abort(); request = null; } } }
调用方式
var reval = ReturnFromGetHttp("http://www.douyou100.com");
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。