private void EndPostResponse(IAsyncResult result) { //结束异步请求,获取结果 HttpWebRequest webRequest = null; WebResponse webResponse = null; string url = null; try { webRequest = (HttpWebRequest)result.AsyncState; webResponse = webRequest.EndGetResponse(result); //把输出结果转化 Stream answer = webResponse.GetResponseStream(); // var encode=Encoding.GetEncoding("utf-8"); var encode = Encoding.UTF8; StreamReader answerData = new StreamReader(answer, encode); //触发完毕事件 url = webRequest.RequestUri.AbsoluteUri; string responseData = answerData.ReadToEnd(); if (null != this.OnPostUrlRequestCompleted) { var agrs = new HTTPRequestCompletedAgrs { URL = url, Content = responseData }; this.OnPostUrlRequestCompleted.Invoke(this, agrs); } //及时释放资源 answer.Dispose(); answerData.Dispose(); } catch (Exception ex) { if (null != this.OnPostUrlRequestCompleted) { var agrs = new HTTPRequestCompletedAgrs { URL = url, Content = null, Error = ex }; this.OnPostUrlRequestCompleted.Invoke(this, agrs); } } finally { if (null != webResponse) { webResponse.Close(); } } }
/// <summary> /// 发送异步的HTTP -GET请求 /// </summary> /// <param name="url"></param> /// <param name="timeout"></param> /// <param name="cookies"></param> public void CreateGetAsync(string url, NameValueCollection requestHeaders, int?timeout, CookieCollection cookies = null) { ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; //webReq.ContentType = "text/html;charset=utf-8"; request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; request.UserAgent = DefaultUserAgent; request.AllowAutoRedirect = true; request.KeepAlive = true; request.CookieContainer = GlobleCookieContainer; request.Timeout = 3000; if (timeout.HasValue) { request.Timeout = timeout.Value; } this.FormarRequestHeaders(request, requestHeaders); try { //开启异步请求 IAsyncResult result = request.BeginGetResponse(new AsyncCallback(EndGetResponse), request); } catch (Exception ex) { //未能连接请求 那么通知事件 已经触发,返回结果为空 if (null != this.OnGetUrlRequestCompleted) { var agrs = new HTTPRequestCompletedAgrs { URL = url, Content = null, Error = ex }; this.OnGetUrlRequestCompleted.Invoke(this, agrs); } } }
/// <summary> /// 创建POST方式的HTTP请求 ,基于异步的请求 /// </summary> /// <param name="url">请求的URL</param> /// <param name="contentType">请求的内容类型</param> /// <param name="parameters">随同请求POST的参数名称及参数值字典</param> /// <param name="timeout">请求的超时时间</param> /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param> /// <param name="requestEncoding">发送HTTP请求时所用的编码</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param> /// <returns></returns> public void CreatePostHttpResponseAsync(string url, NameValueCollection requestHeaders, string contentType, IDictionary <string, string> parameters, int?timeout = null, CookieContainer cookies = null) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } //获取域名 string domainName = GetDomainName(url); //设置默认的编码 UFT-8 Encoding requestEncoding = Encoding.UTF8; HttpWebRequest request = null; //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST"; request.ContentType = contentType; request.CookieContainer = GlobleCookieContainer; request.UserAgent = DefaultUserAgent; if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = cookies; } this.FormarRequestHeaders(request, requestHeaders); //如果需要POST数据 if (!(parameters == null || parameters.Count == 0)) { if (contentType == FormDataType.Json) { // StringBuilder buffer = new StringBuilder(); // buffer.AppendFormat("{0}", parameters.First().Value);//json 必须是一个整体的包结构 //传递Json 数据包 必须是 UTF-8编码。。。javascript 设计如此 requestEncoding = Encoding.UTF8; ///json 必须是一个整体的包结构,而且不要 转码 string paraBag = parameters.First().Value; byte[] data = requestEncoding.GetBytes(paraBag);//requestEncoding.GetBytes(buffer.ToString()); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); stream.Flush(); } } else if (contentType == FormDataType.StandForm) { StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, HttpUtility.UrlEncode(parameters[key])); } else { buffer.AppendFormat("{0}={1}", key, HttpUtility.UrlEncode(parameters[key])); } i++; } byte[] data = requestEncoding.GetBytes(buffer.ToString()); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } } try { //开启异步请求 IAsyncResult result = request.BeginGetResponse(new AsyncCallback(EndPostResponse), request); } catch (Exception ex) { //未能连接请求 那么通知事件 已经触发,返回结果为空 if (null != this.OnPostUrlRequestCompleted) { var agrs = new HTTPRequestCompletedAgrs { URL = url, Content = null, Error = ex }; this.OnPostUrlRequestCompleted.Invoke(this, agrs); } } }
/// <summary> /// 创建GET方式的HTTP请求 /// </summary> /// <param name="url">请求的URL</param> /// <param name="timeout">请求的超时时间</param> /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param> /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param> /// <returns></returns> public HttpWebResponse CreateGetHttpResponse(string url, NameValueCollection requestHeaders, int?timeout = 5000, CookieContainer cookies = null) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } //获取域名 string domainName = GetDomainName(url); HttpWebRequest request = null;// WebRequest.Create(url) as HttpWebRequest; //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } //---------固定的头--begin----------- request.Method = "GET"; request.UserAgent = DefaultUserAgent; request.CookieContainer = cookies;//设定为共享Cookie容器 request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8"); //---------固定的头----end------------ request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"; request.KeepAlive = true; request.Timeout = timeout.Value; // request.Host = "s.click.taobao.com"; // request.Headers.Add("Upgrade-Insecure-Requests", "1"); this.FormarRequestHeaders(request, requestHeaders); if (cookies != null) { request.CookieContainer = cookies; } try { var response = request.GetResponse() as HttpWebResponse; return(response); } catch (Exception ex) { if (null != this.OnGetUrlRequestCompleted) { var args = new HTTPRequestCompletedAgrs() { URL = url, Content = null, Error = ex }; this.OnGetUrlRequestCompleted.Invoke(this, args); } return(null); } }