HttpWebRequest

 新增了证书信息的添加

 

Request 

封装一个请求信息类

  1 using System.Collections.Generic;
  2 using System.Net;
  3 using System.Text;
  4 
  5 using Notify.Solution.Code.Common.Enum;
  6 
  7 namespace Notify.Solution.Code.Common.Model
  8 {
  9     /// <summary>
 10     /// The request.
 11     /// </summary>
 12     public class Request
 13     {
 14         /// <summary>
 15         /// Initializes a new instance of the <see cref="Request"/> class.
 16         /// </summary>
 17         /// <param name="url">
 18         /// The url.
 19         /// </param>
 20         public Request(string url)
 21         {
 22             this.Url = url;
 23         }
 24 
 25         /// <summary>
 26         /// 请求目标地址
 27         /// </summary>
 28         public string Url { get; private set; }
 29 
 30         /// <summary>
 31         /// Referer HTTP 标头的值
 32         /// </summary>
 33         public string Referer { get; set; }
 34 
 35         /// <summary>
 36         /// Cookie
 37         /// </summary>
 38         public CookieContainer Cookie { get; set; }
 39 
 40         /// <summary>
 41         /// 代理
 42         /// </summary>
 43         public WebProxy Proxy { get; set; }
 44 
 45         /// <summary>
 46         /// 请求方式
 47         /// </summary>
 48         public HttpMethod HttpMethod { get; set; }
 49 
 50         /// <summary>
 51         /// 参数编码格式
 52         /// </summary>
 53         private Encoding encoding = Encoding.UTF8;
 54 
 55         /// <summary>
 56         /// 参数编码格式
 57         /// </summary>
 58         public Encoding Encoding
 59         {
 60             get
 61             {
 62                 return this.encoding;
 63             }
 64 
 65             set
 66             {
 67                 this.encoding = value;
 68             }
 69         }
 70 
 71         /// <summary>
 72         /// 是否与 Internet 资源建立持久性连接。
 73         /// </summary>
 74         public bool KeepAlive { get; set; }
 75 
 76         /// <summary>
 77         /// 请求超时时间
 78         /// </summary>
 79         private int timeout = 30 * 0x3e8;
 80 
 81         /// <summary>
 82         /// 请求超时时间(单位毫秒)
 83         /// </summary>
 84         public int Timeout
 85         {
 86             get
 87             {
 88                 return this.timeout;
 89             }
 90 
 91             set
 92             {
 93                 this.timeout = value;
 94             }
 95         }
 96 
 97         /// <summary>
 98         /// 请求参数
 99         /// </summary>
100         public IDictionary<string, string> Parameters { get; set; }
101 
102         /// <summary>
103         /// 证书
104         /// </summary>
105         public Certificate Certificate { get; set; }
106     }
107 
108     /// <summary>
109     /// 证书
110     /// </summary>
111     public class Certificate
112     {
113         /// <summary>
114         /// 证书地址
115         /// </summary>
116         public string CertFile { get; set; }
117 
118         /// <summary>
119         /// 证书密码
120         /// </summary>
121         public string CertPasswd { get; set; }
122     }
123 }

 

请求类返回一个Stream 对象

GetStream

该方法主要创建 一个http请求 和响应http内容处理

 var httpWebRequest = GetHttpWebRequest(request);

创建http请求 和响应参数设置

 response = (HttpWebResponse)httpWebRequest.GetResponse();

响应http内容

  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using System.Linq;
  5 using System.Net;
  6 using System.Net.Cache;
  7 
  8 using Notify.Solution.Code.Common.Enum;
  9 using Notify.Solution.Code.Common.Model;
 10 using Notify.Solution.Code.Extension;
 11 
 12 namespace Notify.Solution.Code.Utility
 13 {
 14     using System.Security.Cryptography.X509Certificates;
 15 
 16     using Exception = System.Exception;
 17 
 18     /// <summary>
 19     /// The http utility.
 20     /// </summary>
 21     internal static class HttpRequestUtility
 22     {
 23         /// <summary>
 24         /// GetStream
 25         /// </summary>
 26         /// <param name="request">request</param>
 27         /// <returns>Stream</returns>
 28         internal static Stream GetStream(Request request)
 29         {
 30             HttpWebResponse response = null;
 31             Stream responseStream = null;
 32             try
 33             {
 34                 var httpWebRequest = GetHttpWebRequest(request);
 35                 response = (HttpWebResponse)httpWebRequest.GetResponse();
 36                 responseStream = response.GetResponseStream();
 37                 byte[] buffer = StreamToBytes(responseStream);
 38                 Stream memoryStream = new MemoryStream(buffer);
 39                 request.Cookie = httpWebRequest.CookieContainer;
 40                 return memoryStream;
 41             }
 42             catch (Exception)
 43             {
 44                 return null;
 45             }
 46             finally
 47             {
 48                 if (responseStream != null)
 49                 {
 50                     responseStream.Dispose();
 51                     responseStream.Close();
 52                 }
 53 
 54                 if (response != null)
 55                 {
 56                     response.Dispose();
 57                     response.Close();
 58                 }
 59             }
 60         }
 61 
 62         /// <summary>
 63         /// GteParameters
 64         /// </summary>
 65         /// <param name="parameters">parameters</param>
 66         /// <returns>string</returns>
 67         private static string GteParameters(IDictionary<string, string> parameters)
 68         {
 69             if (parameters == null || !parameters.Any())
 70             {
 71                 return string.Empty;
 72             }
 73 
 74             return parameters.Join("&", p => p.Key + "=" + p.Value);
 75         }
 76 
 77         /// <summary>
 78         /// CreateUri
 79         /// </summary>
 80         /// <param name="request">url</param>
 81         /// <returns>Uri</returns>
 82         private static Uri CreateUri(Request request)
 83         {
 84             if (string.IsNullOrEmpty(request.Url))
 85             {
 86                 throw new ArgumentNullException("url");
 87             }
 88 
 89             string url = request.Url;
 90             if (request.HttpMethod == HttpMethod.Get)
 91             {
 92                 string parameters = GteParameters(request.Parameters);
 93                 url = url + "?" + parameters;
 94             }
 95 
 96             Uri uri;
 97             if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri))
 98             {
 99                 return uri;
100             }
101             else
102             {
103                 throw new ArgumentException("请求目标地址格式错误");
104             }
105         }
106 
107         /// <summary>
108         /// 设置请求基本信息
109         /// </summary>
110         /// <param name="request">request</param>
111         /// <returns>HttpWebRequest</returns>
112         private static HttpWebRequest GetHttpWebRequest(Request request)
113         {
114             Uri uri = CreateUri(request);
115             HttpWebRequest webRequest = WebRequest.CreateHttp(uri);
116             HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
117             webRequest.CachePolicy = policy;
118             webRequest.Timeout = request.Timeout;
119             webRequest.KeepAlive = request.KeepAlive;
120             webRequest.Method = request.HttpMethod.ToString();
121             webRequest.CookieContainer = request.Cookie;
122             webRequest.Referer = request.Referer;
123             webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1; .NET CLR 2.0.1124)";
124             webRequest.Headers.Add("Cache-Control", "no-cache");
125             webRequest.Accept = "*/*";
126             webRequest.Credentials = CredentialCache.DefaultCredentials;
127 
128             SetProxy(webRequest, request);
129 
130             SetCertificate(webRequest, request);
131 
132             SetParameters(webRequest, request);
133 
134             return webRequest;
135         }
136 
137         /// <summary>
138         /// 设置代理信息
139         /// </summary>
140         /// <param name="webRequest">httpWebRequest</param>
141         /// <param name="request">request</param>
142         private static void SetProxy(WebRequest webRequest, Request request)
143         {
144             if (request.Proxy != null)
145             {
146                 webRequest.Proxy = request.Proxy;
147             }
148         }
149 
150         /// <summary>
151         /// 设置请求证书
152         /// </summary>
153         /// <param name="webRequest">httpWebRequest</param>
154         /// <param name="request">request</param>
155         private static void SetCertificate(HttpWebRequest webRequest, Request request)
156         {
157             if (request.Certificate != null)
158             {
159                 try
160                 {
161                     webRequest.ClientCertificates.Add(new X509Certificate2(request.Certificate.CertFile, request.Certificate.CertPasswd, X509KeyStorageFlags.MachineKeySet));
162                 }
163                 catch (Exception)
164                 {
165                     X509Store store = new X509Store("My", StoreLocation.LocalMachine);
166                     store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
167                     X509Certificate2 cert = store.Certificates.Find(X509FindType.FindBySubjectName, request.Certificate.CertPasswd, false)[0];
168                     webRequest.ClientCertificates.Add(cert);
169                 }
170             }
171         }
172 
173         /// <summary>
174         /// 设置请求参数信息
175         /// </summary>
176         /// <param name="webRequest">httpWebRequest</param>
177         /// <param name="request">request</param>
178         private static void SetParameters(WebRequest webRequest, Request request)
179         {
180             if (request.HttpMethod == HttpMethod.Post)
181             {
182                 string parameters = GteParameters(request.Parameters);
183                 byte[] bytes = request.Encoding.GetBytes(parameters);
184                 webRequest.ContentType = "application/x-www-form-urlencoded";
185                 webRequest.ContentLength = bytes.Length;
186                 using (Stream requestStream = webRequest.GetRequestStream())
187                 {
188                     requestStream.Write(bytes, 0, bytes.Length);
189                 }
190             }
191         }
192 
193         /// <summary>
194         /// 数据流转换
195         /// </summary>
196         /// <param name="stream">数据流</param>
197         /// <returns>字节数组</returns>
198         private static byte[] StreamToBytes(Stream stream)
199         {
200             List<byte> bytes = new List<byte>();
201             int temp = stream.ReadByte();
202             while (temp != -1)
203             {
204                 bytes.Add((byte)temp);
205                 temp = stream.ReadByte();
206             }
207 
208             return bytes.ToArray();
209         }
210     }
211 }

 

对应请求的内容处理

返回的内容可能是 超文本内容 或者 是图片等

    /// <summary>
    /// The http request html.
    /// </summary>
    public class HttpRequestService
    {
        /// <summary>
        /// 获取一个文本内容
        /// </summary>
        /// <param name="request">
        /// 请求信息
        /// </param>
        /// <returns>
        /// 结果
        /// </returns>
        public static string GetHttpRequest(Request request)
        {
            try
            {
                var stream = HttpRequestUtility.GetStream(request);
                using (StreamReader sr = new StreamReader(stream, request.Encoding))
                {
                    StringBuilder builder = new StringBuilder();
                    while (sr.Peek() != -1)
                    {
                        builder.Append(sr.ReadLine());
                    }

                    return builder.ToString();
                }
            }
            catch (System.Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 获取一张图片
        /// </summary>
        /// <param name="request">请求信息</param>
        /// <returns>图片</returns>
        public static Bitmap GetImage(Request request)
        {
            Bitmap map = null;
            Stream stream = null;
            try
            {
                stream = HttpRequestUtility.GetStream(request);
                byte[] buf = new byte[stream.Length];
                stream.Read(buf, 0, (int)stream.Length);
                map = new Bitmap(System.Drawing.Image.FromStream(stream));
                return map;
            }
            catch (System.Exception)
            {
                return null;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }

                if (map != null)
                {
                    map.Dispose();
                }
            }
        }
    }

 

4.5处理方法

posted @ 2015-06-29 16:36  刘小吉  阅读(715)  评论(0编辑  收藏  举报