zoukankan      html  css  js  c++  java
  • ahjesus HttpQuery

      1     /// <summary>  
      2     /// 有关HTTP请求的辅助类  
      3     /// </summary>  
      4     public class HttpQuery
      5     {
      6         private static readonly string DefaultUserAgent =
      7             "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
      8 
      9         public static void Get(string url, object data, Action<string> callback)
     10         {
     11             IDictionary<string, string> parameters = Getparameters(data);
     12 
     13             if (!(parameters == null || parameters.Count == 0))
     14             {
     15                 url += "?";
     16                 foreach (var item in parameters)
     17                 {
     18                     url += item.Key + "=" + item.Value + "&";
     19                 }
     20             }
     21             CreateGetHttpResponse(url, null, null, null, callback);
     22         }
     23 
     24         public static void Post(string url, object data, Action<string> callback)
     25         {
     26             IDictionary<string, string> parameters = Getparameters(data);
     27 
     28             CreatePostHttpResponse(url, parameters, null, null, Encoding.UTF8, null, callback);
     29         }
     30 
     31         public static void Post(string url, string data, Action<string> callback)
     32         {
     33             CreatePostHttpResponse(url, data, null, null, Encoding.UTF8, null, callback);
     34         }
     35 
     36         private static IDictionary<string, string> Getparameters(object data)
     37         {
     38             if (data == null)
     39             {
     40                 return new Dictionary<string, string>();
     41             }
     42             IDictionary<string, string> parameters = new Dictionary<string, string>();
     43 
     44             Type type = data.GetType();
     45             PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
     46             foreach (PropertyInfo p in props)
     47             {
     48                 parameters.Add(p.Name, p.GetValue(data).ToString());
     49             }
     50 
     51             return parameters;
     52         }
     53 
     54         /// <summary>  
     55         /// 创建GET方式的HTTP请求  
     56         /// </summary>  
     57         /// <param name="url">请求的URL</param>  
     58         /// <param name="timeout">请求的超时时间</param>  
     59         /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
     60         /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
     61         /// <returns></returns>  
     62         private static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent,
     63             CookieCollection cookies, Action<string> callback, string encoding = "utf-8")
     64         {
     65             if (string.IsNullOrEmpty(url))
     66             {
     67                 return null;
     68                 //throw new ArgumentNullException("url");
     69             }
     70             try
     71             {
     72                 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
     73                 request.Method = "GET";
     74                 request.UserAgent = DefaultUserAgent;
     75                 if (!string.IsNullOrEmpty(userAgent))
     76                 {
     77                     request.UserAgent = userAgent;
     78                 }
     79                 if (timeout.HasValue)
     80                 {
     81                     request.Timeout = timeout.Value;
     82                 }
     83                 if (cookies != null)
     84                 {
     85                     request.CookieContainer = new CookieContainer();
     86                     request.CookieContainer.Add(cookies);
     87                 }
     88 
     89                 HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;
     90 
     91                 StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
     92                     System.Text.Encoding.GetEncoding(encoding));
     93 
     94                 string html = "";
     95                 //获取请求到的数据
     96                 html = reader.ReadToEnd();
     97                 //关闭
     98                 httpWebResponse.Close();
     99                 reader.Close();
    100 
    101                 Regex regex = new Regex("charset=(?<code>\w+)"");
    102                 Match match = regex.Match(html);
    103                 string code = match.Groups["code"].Value;
    104                 if (!string.IsNullOrWhiteSpace(code) && code.ToLower() != encoding.ToLower())
    105                 {
    106                     return CreateGetHttpResponse(url, timeout, userAgent, cookies, callback, code);
    107                 }
    108                 else
    109                 {
    110                     callback(html);
    111                     return httpWebResponse;
    112                 }
    113             }
    114             catch
    115             {
    116                 callback(null);
    117             }
    118             return null;
    119         }
    120 
    121         /// <summary>  
    122         /// 创建POST方式的HTTP请求  
    123         /// </summary>  
    124         /// <param name="url">请求的URL</param>  
    125         /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>  
    126         /// <param name="timeout">请求的超时时间</param>  
    127         /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
    128         /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>  
    129         /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
    130         /// <returns></returns>  
    131         private static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters,
    132             int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies, Action<string> callback)
    133         {
    134             if (string.IsNullOrEmpty(url))
    135             {
    136                 throw new ArgumentNullException("url");
    137             }
    138             if (requestEncoding == null)
    139             {
    140                 throw new ArgumentNullException("requestEncoding");
    141             }
    142             HttpWebRequest request = null;
    143             try
    144             {
    145                 //如果是发送HTTPS请求  
    146                 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    147                 {
    148                     ServicePointManager.ServerCertificateValidationCallback =
    149                         new RemoteCertificateValidationCallback(CheckValidationResult);
    150                     request = WebRequest.Create(url) as HttpWebRequest;
    151                     request.ProtocolVersion = HttpVersion.Version10;
    152                 }
    153                 else
    154                 {
    155                     request = WebRequest.Create(url) as HttpWebRequest;
    156                 }
    157                 request.Method = "POST";
    158                 request.ContentType = "application/x-www-form-urlencoded";
    159 
    160                 if (!string.IsNullOrEmpty(userAgent))
    161                 {
    162                     request.UserAgent = userAgent;
    163                 }
    164                 else
    165                 {
    166                     request.UserAgent = DefaultUserAgent;
    167                 }
    168 
    169                 if (timeout.HasValue)
    170                 {
    171                     request.Timeout = timeout.Value;
    172                 }
    173                 if (cookies != null)
    174                 {
    175                     request.CookieContainer = new CookieContainer();
    176                     request.CookieContainer.Add(cookies);
    177                 }
    178                 //如果需要POST数据  
    179                 if (!(parameters == null || parameters.Count == 0))
    180                 {
    181                     StringBuilder buffer = new StringBuilder();
    182                     int i = 0;
    183                     foreach (string key in parameters.Keys)
    184                     {
    185                         if (i > 0)
    186                         {
    187                             buffer.AppendFormat("&{0}={1}", key, parameters[key]);
    188                         }
    189                         else
    190                         {
    191                             buffer.AppendFormat("{0}={1}", key, parameters[key]);
    192                         }
    193                         i++;
    194                     }
    195                     byte[] data = requestEncoding.GetBytes(buffer.ToString());
    196                     using (Stream stream = request.GetRequestStream())
    197                     {
    198                         stream.Write(data, 0, data.Length);
    199                     }
    200                 }
    201 
    202                 HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;
    203 
    204                 StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
    205                     System.Text.Encoding.GetEncoding("utf-8"));
    206 
    207                 string html = "";
    208                 //获取请求到的数据
    209                 html = reader.ReadToEnd();
    210 
    211                 //关闭
    212                 httpWebResponse.Close();
    213                 reader.Close();
    214 
    215                 callback(html);
    216 
    217                 return httpWebResponse;
    218             }
    219             catch
    220             {
    221                 callback(null);
    222             }
    223             return null;
    224         }
    225 
    226         private static HttpWebResponse CreatePostHttpResponse(string url, string parameters, int? timeout,
    227             string userAgent, Encoding requestEncoding, CookieCollection cookies, Action<string> callback)
    228         {
    229             if (string.IsNullOrEmpty(url))
    230             {
    231                 return null;
    232                 //throw new ArgumentNullException("url");
    233             }
    234             if (requestEncoding == null)
    235             {
    236                 throw new ArgumentNullException("requestEncoding");
    237             }
    238             HttpWebRequest request = null;
    239             try
    240             {
    241                 //如果是发送HTTPS请求  
    242                 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
    243                 {
    244                     ServicePointManager.ServerCertificateValidationCallback =
    245                         new RemoteCertificateValidationCallback(CheckValidationResult);
    246                     request = WebRequest.Create(url) as HttpWebRequest;
    247                     request.ProtocolVersion = HttpVersion.Version10;
    248                 }
    249                 else
    250                 {
    251                     request = WebRequest.Create(url) as HttpWebRequest;
    252                 }
    253                 request.Method = "POST";
    254                 request.ContentType = "application/x-www-form-urlencoded";
    255 
    256                 if (!string.IsNullOrEmpty(userAgent))
    257                 {
    258                     request.UserAgent = userAgent;
    259                 }
    260                 else
    261                 {
    262                     request.UserAgent = DefaultUserAgent;
    263                 }
    264 
    265                 if (timeout.HasValue)
    266                 {
    267                     request.Timeout = timeout.Value;
    268                 }
    269                 if (cookies != null)
    270                 {
    271                     request.CookieContainer = new CookieContainer();
    272                     request.CookieContainer.Add(cookies);
    273                 }
    274                 //如果需要POST数据  
    275                 if (!string.IsNullOrEmpty(parameters))
    276                 {
    277                     using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    278                     {
    279                         streamWriter.Write(parameters);
    280                         streamWriter.Flush();
    281                     }
    282                 }
    283 
    284                 HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;
    285 
    286                 StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
    287                     System.Text.Encoding.GetEncoding("utf-8"));
    288 
    289                 string html = "";
    290                 //获取请求到的数据
    291                 html = reader.ReadToEnd();
    292 
    293                 //关闭
    294                 httpWebResponse.Close();
    295                 reader.Close();
    296 
    297                 callback(html);
    298 
    299                 return httpWebResponse;
    300             }
    301             catch
    302             {
    303                 callback(null);
    304             }
    305             return null;
    306         }
    307 
    308         private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain,
    309             SslPolicyErrors errors)
    310         {
    311             return true; //总是接受  
    312         }
    313 
    314     }
    View Code

    使用方法

    HttpQuery.Post(url, new { key = key, xmlCount = xmlCount }, (msg) =>
                {
                    
                });
  • 相关阅读:
    Leetcode Substring with Concatenation of All Words
    Leetcode Divide Two Integers
    Leetcode Edit Distance
    Leetcode Longest Palindromic Substring
    Leetcode Longest Substring Without Repeating Characters
    Leetcode 4Sum
    Leetcode 3Sum Closest
    Leetcode 3Sum
    Leetcode Candy
    Leetcode jump Game II
  • 原文地址:https://www.cnblogs.com/ahjesus/p/4174857.html
Copyright © 2011-2022 走看看