HttpWebRequest HttpClient

来源:互联网 发布:简单无线mesh网络搭建 编辑:程序博客网 时间:2024/05/16 07:49

原文地址:http://www.cnblogs.com/tongyi/p/6702326.html

HttpWebRequest HttpClient 简单封装使用,支持https

HttpWebRequest

复制代码
  1 using System;  2 using System.Collections.Generic;  3 using System.IO;  4 using System.IO.Compression;  5 using System.Linq;  6 using System.Net;  7 using System.Net.Security;  8 using System.Security.Cryptography.X509Certificates;  9 using System.Text; 10 using TT.Utilities.Extends; 11  12 namespace TT.Utilities.Web 13 { 14     public class HttpRequest 15     { 16         public static HttpWebRequest CreateHttpWebRequest(string url) 17         { 18             HttpWebRequest request; 19             //如果是发送HTTPS请求   20             if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) 21             { 22                 //ServicePointManager.DefaultConnectionLimit = 1000; 23                 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); 24                 request = WebRequest.Create(url) as HttpWebRequest; 25                 request.ProtocolVersion = HttpVersion.Version11; 26             } 27             else 28             { 29                 request = WebRequest.Create(url) as HttpWebRequest; 30             } 31             request.Proxy = null; 32             request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); 33             return request; 34         } 35  36         /// <summary> 37         ///  38         /// </summary> 39         /// <param name="url">url</param> 40         /// <param name="dic">参数</param> 41         /// <param name="headerDic">请求头参数</param> 42         /// <returns></returns> 43         public static string DoPost(string url, Dictionary<string, string> dic, Dictionary<string, string> headerDic) 44         { 45             HttpWebRequest request = CreateHttpWebRequest(url); 46             request.Method = "POST"; 47             request.Accept = "*/*"; 48             request.ContentType = HttpContentTypes.GetContentType(HttpContentTypes.HttpContentTypeEnum.JSON); 49             if (headerDic != null && headerDic.Count > 0) 50             { 51                 foreach (var item in headerDic) 52                 { 53                     request.Headers.Add(item.Key, item.Value); 54                 } 55             } 56             if (dic != null && dic.Count > 0) 57             { 58                 var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(dic); 59                 byte[] buffer = Encoding.UTF8.GetBytes(jsonStr); 60                 request.ContentLength = buffer.Length; 61                 try 62                 { 63                     request.GetRequestStream().Write(buffer, 0, buffer.Length); 64                 } 65                 catch (WebException ex) 66                 { 67                     throw ex; 68                 } 69             } 70             else 71             { 72                 request.ContentLength = 0; 73             } 74             return HttpResponse(request); 75         } 76  77         public static string DoPost(string url, Dictionary<string, string> dic) 78         { 79             return DoPost(url, dic, null); 80         } 81  82         static object olock = new object(); 83         public static string HttpResponse(HttpWebRequest request) 84         { 85             try 86             { 87                 //lock (olock) 88                 //{ 89                 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 90                 { 91                     var contentEncodeing = response.ContentEncoding.ToLower(); 92  93                     if (!contentEncodeing.Contains("gzip") && !contentEncodeing.Contains("deflate")) 94                     { 95                         using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) 96                         { 97                             return reader.ReadToEnd(); 98                         } 99                     }100                     else101                     {102                         #region gzip,deflate 压缩解压103                         if (contentEncodeing.Contains("gzip"))104                         {105                             using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))106                             {107                                 using (StreamReader reader = new StreamReader(stream))108                                 {109                                     return reader.ReadToEnd();110                                 }111                             }112                         }113                         else //if (contentEncodeing.Contains("deflate"))114                         {115                             using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))116                             {117                                 using (StreamReader reader = new StreamReader(stream))118                                 {119                                     return reader.ReadToEnd();120                                 }121                             }122                         }123                         #endregion gzip,deflate 压缩解压124                     }125                 }126                 //}127             }128             catch (WebException ex)129             {130                 throw ex;131             }132         }133 134         public static string DoGet(string url, Dictionary<string, string> dic)135         {136             try137             {138                 var argStr = dic == null ? "" : dic.ToSortUrlParamString();139                 argStr = string.IsNullOrEmpty(argStr) ? "" : ("?" + argStr);140                 HttpWebRequest request = CreateHttpWebRequest(url + argStr);141                 request.Method = "GET";142                 request.ContentType = "application/json";143                 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())144                 {145                     using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))146                     {147                         return reader.ReadToEnd();148                     }149                 }150             }151             catch (Exception ex)152             {153                 throw ex;154             }155         }156 157         public static string DoGet(string url, Dictionary<string, string> dic, Dictionary<string, string> headerDic)158         {159             try160             {161                 var argStr = dic == null ? "" : dic.ToSortUrlParamString();162                 argStr = string.IsNullOrEmpty(argStr) ? "" : ("?" + argStr);163                 HttpWebRequest request = CreateHttpWebRequest(url + argStr);164                 request.Method = "GET";165                 request.ContentType = "application/json";166                 foreach (var item in headerDic)167                 {168                     request.Headers.Add(item.Key, item.Value);169                 }170                 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())171                 {172                     using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))173                     {174                         return reader.ReadToEnd();175                     }176                 }177             }178             catch (Exception ex)179             {180                 throw ex;181             }182         }183 184         private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)185         {186             return true; //总是接受  187         }188     }189 }
复制代码

HttpClient

复制代码
  1 using System;  2 using System.Collections.Generic;  3 using System.Linq;  4 using System.Text;  5 using System.Net;  6 using System.Net.Http;  7 using System.Net.Http.Headers;  8 using TT.Utilities.Extends;  9 using System.Net.Security; 10 using System.Security.Cryptography.X509Certificates; 11  12 namespace TT.Utilities.Web 13 { 14     public class HttpClientUti 15     { 16         /// <summary> 17         /// post 提交json格式参数 18         /// </summary> 19         /// <param name="url">url</param> 20         /// <param name="postJson">json字符串</param> 21         /// <returns></returns> 22         public static string DoPost(string url, string postJson) 23         { 24             HttpContent content = new StringContent(postJson); 25             content.Headers.ContentType = new MediaTypeHeaderValue(HttpContentTypes.GetContentType(HttpContentTypes.HttpContentTypeEnum.JSON)); 26             return DoPost(url, content); 27         } 28  29         /// <summary> 30         /// post 提交json格式参数 31         /// </summary> 32         /// <param name="url">url</param> 33         /// <param name="argDic">参数字典</param> 34         /// <param name="headerDic">请求头字典</param> 35         /// <returns></returns> 36         public static string DoPost(string url, Dictionary<string, string> argDic, Dictionary<string, string> headerDic) 37         { 38             argDic.ToSortUrlParamString(); 39             var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(argDic); 40             HttpContent content = new StringContent(jsonStr); 41             content.Headers.ContentType = new MediaTypeHeaderValue(HttpContentTypes.GetContentType(HttpContentTypes.HttpContentTypeEnum.JSON)); 42             if (headerDic != null) 43             { 44                 foreach (var item in headerDic) 45                 { 46                     content.Headers.Add(item.Key, item.Value); 47                 } 48             } 49             return DoPost(url, content); 50         } 51  52         /// <summary> 53         /// HttpClient POST 提交 54         /// </summary> 55         /// <param name="url">url</param> 56         /// <param name="content">HttpContent</param> 57         /// <returns></returns> 58         public static string DoPost(string url, HttpContent content) 59         { 60             try 61             { 62                 var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; 63                 using (var http = new HttpClient(handler)) 64                 { 65                     if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) 66                     { 67                         ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); 68                     } 69  70                     var response = http.PostAsync(url, content).Result; 71                     //确保HTTP成功状态值 72                     response.EnsureSuccessStatusCode(); 73                     //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip) 74                     var reJson = response.Content.ReadAsStringAsync().Result; 75                     return reJson; 76                 } 77             } 78             catch (Exception ex) 79             { 80                 throw ex; 81             } 82         } 83  84         /// <summary> 85         /// HttpClient实现Get请求 86         /// </summary> 87         public static string DoGet(string url) 88         { 89             try 90             { 91                 var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; 92                 using (var http = new HttpClient(handler)) 93                 { 94                     var response = http.GetAsync(url).Result; 95                     response.EnsureSuccessStatusCode(); 96                     return response.Content.ReadAsStringAsync().Result; 97                 } 98             } 99             catch (Exception ex)100             {101                 return ex.Message + "," + ex.Source + "," + ex.StackTrace;102             }103         }104 105         /// <summary>106         /// HttpClient实现Get请求107         /// <param name="arg">参数字典</param>108         /// </summary>109         public static string DoGet(string url, IDictionary<string, string> arg)110         {111             var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };112             string argStr = "?";113             foreach (var item in arg)114             {115                 argStr += item.Key + "=" + item.Value + "&";116             }117             argStr = argStr.TrimEnd('&');118             url = url + argStr;119             return DoGet(url);120         }121 122         /// <summary>123         /// HttpClient Get 提交124         /// </summary>125         /// <param name="url"></param>126         /// <param name="arg"></param>127         /// <param name="headerDic"></param>128         /// <returns></returns>129         public static string DoGet(string url, IDictionary<string, string> arg, IDictionary<string, string> headerDic)130         {131             try132             {133                 var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };134                 if (arg != null && arg.Count > 0)135                 {136                     string argStr = "?";137                     foreach (var item in arg)138                     {139                         argStr += item.Key + "=" + item.Value + "&";140                     }141                     argStr = argStr.TrimEnd('&');142                     url = url + argStr;143                 }144                 using (var http = new HttpClient(handler))145                 {146                     if (headerDic != null)147                     {148                         foreach (var item in headerDic)149                         {150                             http.DefaultRequestHeaders.Add(item.Key, item.Value);151                         }152                     }153                     //await异步等待回应154                     var response = http.GetStringAsync(url).Result;155                     return response;156                 }157             }158             catch (Exception ex)159             {160                 throw ex;161             }162         }163 164         private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)165         {166             return true; //总是接受  167         } 168     }169 }
复制代码

单例模式 HttpClient

复制代码
  1 using System;  2 using System.Collections.Generic;  3 using System.Linq;  4 using System.Text;  5 using System.Net;  6 using System.Net.Http;  7 using System.Net.Http.Headers;  8 using TT.Utilities.Extends;  9 using System.Security.Cryptography.X509Certificates; 10 using System.Net.Security; 11  12 namespace TT.Utilities.Web 13 { 14     public class HttpClientSingleton 15     { 16         public static readonly HttpClient http = null; 17         static HttpClientSingleton() 18         { 19             var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; 20             ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult; 21             http = new HttpClient(handler); 22         } 23  24         /// <summary> 25         /// post 提交json格式参数 26         /// </summary> 27         /// <param name="url">url</param> 28         /// <param name="postJson">json字符串</param> 29         /// <returns></returns> 30         public static string DoPost(string url, string postJson) 31         { 32             HttpContent content = new StringContent(postJson); 33             content.Headers.ContentType = new MediaTypeHeaderValue(HttpContentTypes.GetContentType(HttpContentTypes.HttpContentTypeEnum.JSON)); 34             return DoPost(url, content); 35         } 36  37         /// <summary> 38         /// post 提交json格式参数 39         /// </summary> 40         /// <param name="url">url</param> 41         /// <param name="argDic">参数字典</param> 42         /// <param name="headerDic">请求头字典</param> 43         /// <returns></returns> 44         public static string DoPost(string url, Dictionary<string, string> argDic, Dictionary<string, string> headerDic) 45         { 46             argDic.ToSortUrlParamString(); 47             var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(argDic); 48             HttpContent content = new StringContent(jsonStr); 49             content.Headers.ContentType = new MediaTypeHeaderValue(HttpContentTypes.GetContentType(HttpContentTypes.HttpContentTypeEnum.JSON)); 50             if (headerDic != null) 51             { 52                 foreach (var item in headerDic) 53                 { 54                     content.Headers.Add(item.Key, item.Value); 55                 } 56             } 57             return DoPost(url, content); 58         } 59  60         /// <summary> 61         /// HttpClient POST 提交 62         /// </summary> 63         /// <param name="url">url</param> 64         /// <param name="content">HttpContent</param> 65         /// <returns></returns> 66         public static string DoPost(string url, HttpContent content) 67         { 68             try 69             { 70                 var response = http.PostAsync(url, content).Result; 71                 //确保HTTP成功状态值 72                 response.EnsureSuccessStatusCode(); 73                 //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip) 74                 var reJson = response.Content.ReadAsStringAsync().Result; 75                 return reJson; 76             } 77             catch (Exception ex) 78             { 79                 throw ex; 80             } 81         } 82  83         /// <summary> 84         /// HttpClient实现Get请求 85         /// </summary> 86         public static string DoGet(string url) 87         { 88             try 89             { 90                 var response = http.GetAsync(url).Result; 91                 response.EnsureSuccessStatusCode(); 92                 return response.Content.ReadAsStringAsync().Result; 93             } 94             catch (Exception ex) 95             { 96                 return ex.Message + "," + ex.Source + "," + ex.StackTrace; 97             } 98         } 99 100         /// <summary>101         /// HttpClient实现Get请求102         /// <param name="arg">参数字典</param>103         /// </summary>104         public static string DoGet(string url, IDictionary<string, string> arg)105         {106             string argStr = "?";107             foreach (var item in arg)108             {109                 argStr += item.Key + "=" + item.Value + "&";110             }111             argStr = argStr.TrimEnd('&');112             url = url + argStr;113             return DoGet(url);114         }115 116         /// <summary>117         /// HttpClient Get 提交118         /// </summary>119         /// <param name="url"></param>120         /// <param name="arg"></param>121         /// <param name="headerDic"></param>122         /// <returns></returns>123         public static string DoGet(string url, IDictionary<string, string> arg, IDictionary<string, string> headerDic)124         {125             try126             {127                 if (arg != null && arg.Count > 0)128                 {129                     string argStr = "?";130                     foreach (var item in arg)131                     {132                         argStr += item.Key + "=" + item.Value + "&";133                     }134                     argStr = argStr.TrimEnd('&');135                     url = url + argStr;136                 }137 138                 if (headerDic != null)139                 {140                     foreach (var item in headerDic)141                     {142                         http.DefaultRequestHeaders.Add(item.Key, item.Value);143                     }144                 }145                 //await异步等待回应146                 var response = http.GetStringAsync(url).Result;147                 return response;148 149             }150             catch (Exception ex)151             {152                 throw ex;153             }154         }155 156         private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)157         {158             return true; //总是接受  159         } 160     }161 }
复制代码
复制代码
public class HttpContentTypes    {        public enum HttpContentTypeEnum        {            JSON,            FORM        }        public static string GetContentType(HttpContentTypeEnum type)        {            string typeStr = "";            switch (type)            {                case HttpContentTypeEnum.JSON:                    typeStr = "application/json";                    break;                case HttpContentTypeEnum.FORM:                    typeStr = "application/x-www-form-urlencoded";                    break;            }            return typeStr;        }    }
复制代码

注意HttpClient的使用,推荐HttpWebRequest。

原创粉丝点击