调用接口,数据请求(公共方法)

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 using System.Web;
  7 using System.Net;
  8 using System.IO;
  9 using System.Security.Cryptography.X509Certificates;
 10 using System.Security.Authentication;
 11 using System.Net.Security;
 12 
 13 namespace TravelB2B.Core.Utils
 14 {
 15     public class HttpClient
 16     {
 17         static log4net.ILog logger = log4net.LogManager.GetLogger("HttpClient");
 18 
 19         #region 一般数据请求
 20         public static string WebRequest(Method method, string url, string postData)
 21         {
 22             return WebRequest(method, url, postData, Encoding.UTF8);
 23         }
 24
      示例:

          //string url = "https://www.baidu.com";
          //string data = "client_id=21768513&client_secret=5568ab8e4f17b1a91bc732b289933f7d&grant_type=authorization_code&code=" + code + "&redirect_uri=http://www.juyingzhiye.com/TaoBao/ToTocketResult&state=1212&view=web";
          //string res = TravelB2B.Core.Utils.HttpClient.WebRequest(Core.Utils.Method.POST, url, data);

    

       static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) 26 { 28 return true; 29 } 30 31 public static string WebRequest(Method method, string url, string postData, Dictionary<string, dynamic> header) 32 { 33 return WebRequest(method, url, postData, Encoding.UTF8, header); 34 } 35 36 public static string WebRequest(Method method, string url, string postData, Encoding encoding) 37 { 38 return WebRequest(method, url, postData, encoding,null); 39 } 40 public static string WebRequest(Method method, string url, string postData, Encoding encoding,Dictionary<string,dynamic> header) 41 { 42 string responseData = ""; 43 HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; 44 webRequest.Method = method.ToString(); 45 webRequest.ServicePoint.Expect100Continue = false; 46 47 48 System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^https://", System.Text.RegularExpressions.RegexOptions.IgnoreCase); 49 if (regex.IsMatch(url)) 50 { 51 ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate; 52 } 53 54 if (method == Method.POST || method == Method.PUT) 55 { 56 if (method == Method.POST) 57 { 58 webRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; 59 } 60 if (method == Method.PUT) 61 { 62 webRequest.ContentType = "html/xml"; 63 } 64 if (header != null) 65 { 66 foreach (var item in header) 67 { 68 if (item.Key == "Date") 69 { 70 webRequest.Date = DateTime.Parse(item.Value); 71 } 72 else if (item.Key == "ContentType") 73 { 74 webRequest.ContentType = item.Value; 75 } 76 else 77 { 78 webRequest.Headers[item.Key] = item.Value; 79 } 80 } 81 } 82 byte[] Bytes = encoding.GetBytes(postData); 83 webRequest.ContentLength = Bytes.Length; 84 85 using (Stream requestWriter = webRequest.GetRequestStream()) 86 { 87 try 88 { 89 requestWriter.Write(Bytes, 0, Bytes.Length); 90 } 91 catch 92 { 93 } 94 finally 95 { 96 requestWriter.Close(); 97 } 98 } 99 } 100 101 responseData = WebResponseGet(webRequest, encoding); 102 103 webRequest = null; 104 105 return responseData; 106 107 } 108 109 /// <summary> 110 /// 访问指定页面地址 111 /// </summary> 112 /// <param name="method"></param> 113 /// <param name="url"></param> 114 /// <param name="postData"></param> 115 /// <returns></returns> 116 public static string WebRequest(Method method, string url, IDictionary<string, string> parameters) 117 { 118 return WebRequest(method, url, ToQueryString(parameters)); 119 } 120 121 public static string WebRequest(Method method, string url, IDictionary<string, string> parameters,System.Text.Encoding encoding) 122 { 123 return WebRequest(method, url, ToQueryString(parameters), encoding); 124 } 125     例子:

        //string url = "http://120.27.152.161/stardy/balance.jsp";
        //Dictionary<string, string> para = new Dictionary<string, string>();
        //para.Add("usr", UserName);
        //para.Add("pwd", Password);
        //return TravelB2B.Core.Utils.HttpClient.WebRequest(Utils.Method.POST, url, para, System.Text.Encoding.Default);

126         #endregion
127 
128         #region 带有文字和图片的请求
129         /// <summary>
130         /// 带有文件/图片的请求
131 
132         /// </summary>
133         /// <param name="method"></param>
134         /// <param name="url"></param>
135         /// <param name="postData"></param>
136         /// <returns></returns>
137         public static string WebRequest(Method method, string url, IDictionary<string, string> parameters, FileItem fileItem, Encoding encoding)
138         {
139             string responseData = "";
140             HttpWebRequest webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
141             webRequest.Method = method.ToString();
142             webRequest.ServicePoint.Expect100Continue = false;
143             webRequest.KeepAlive = true;
144             webRequest.UserAgent = "Mozilla/5.0 (Windows; U; zh-CN)";
145 
146             string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
147 
148             if (method == Method.POST || method == Method.PUT)
149             {
150                 webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
151 
152                 using (Stream requestWriter = webRequest.GetRequestStream())
153                 {
154                     try
155                     {
156                         StringBuilder sb = new StringBuilder();
157                         string start = "--" + boundary;
158                         string end = start + "--";
159 
160                         for (int i = 0; i < parameters.Count; i++)
161                         {
162                             sb.Append(start + "
");
163                             sb.Append("Content-Disposition: form-data; name="" + parameters.ElementAt(i).Key + ""

");
164                             sb.Append(parameters.ElementAt(i).Value + "
");
165                         }
166                         sb.Append(start + "
");
167                         sb.Append("Content-Disposition: form-data; name="" + fileItem.Name + ""; filename="" + fileItem.FileName + ""
");
168                         sb.Append("Content-Type: " + fileItem.ContentType + "

");
169                         string content = sb.ToString();
170                         requestWriter.Write(Encoding.UTF8.GetBytes(content), 0, content.Length);
171                         requestWriter.Write(fileItem.Content, 0, fileItem.Content.Length);
172                         string endContent = "
" + end;
173                         requestWriter.Write(Encoding.UTF8.GetBytes(endContent), 0, endContent.Length);
174 
175                     }
176                     catch
177                     {
178                         throw;
179                     }
180                     finally
181                     {
182                         requestWriter.Close();
183                     }
184                 }
185             }
186 
187             responseData = WebResponseGet(webRequest, encoding);
188 
189             webRequest = null;
190 
191             return responseData;
192         }
193 
194         #endregion
195 
196         #region 获取返回数据
197         /// <summary>
198         /// 获取返回数据
199         /// </summary>
200         /// <param name="webRequest"></param>
201         /// <returns></returns>
202         private static string WebResponseGet(HttpWebRequest webRequest, System.Text.Encoding encoding)
203         {
204             HttpWebResponse res = null;
205 
206             try
207             {
208                 res = (HttpWebResponse)webRequest.GetResponse();
209             }
210             catch (WebException ex)
211             {
212                 logger.Error("返回异常:" + ex.ToString());
213                 res = (HttpWebResponse)ex.Response;
214             }
215             using (StreamReader responseReader = new StreamReader(res.GetResponseStream(), encoding))
216             {
217                 string responseData = responseReader.ReadToEnd();
218                 responseReader.Close();
219                 return responseData;
220             }
221         }
222         #endregion
223 
224         #region 将字符串字典里的数据转换成URL查询字符串格式
225 
226         /// <summary>
227         /// 将字符串字典里的数据转换成URL查询字符串格式。
228         /// </summary>
229         /// <param name="dict">字符串字典。</param>
230         /// <returns></returns>
231         public static string ToQueryString(IDictionary<string, string> dict)
232         {
233             if (dict == null)
234                 return string.Empty;
235 
236             if (dict.Count == 0)
237                 return string.Empty;
238 
239             var buffer = new StringBuilder();
240             var count = 0;
241             var end = false;
242 
243             foreach (var key in dict.Keys)
244             {
245                 if (count == dict.Count - 1) end = true;
246 
247                 if (end)
248                     buffer.AppendFormat("{0}={1}", key, dict[key]);
249                 else
250                     buffer.AppendFormat("{0}={1}&", key, dict[key]);
251 
252                 count++;
253             }
254 
255             return buffer.ToString();
256         }
257 
258         #endregion
259     }
260 
261     public enum Method { GET, POST, PUT, DELETE };
262 
263     #region 文件信息
264     public class FileItem
265     {
266         public string ContentType
267         {
268             get;
269             set;
270         }
271 
272         public string Name
273         {
274             get;
275             set;
276         }
277 
278         public string FileName
279         {
280             get;
281             set;
282         }
283 
284         public byte[] Content
285         {
286             get;
287             set;
288         }
289     }
290     #endregion 
291 }
原文地址:https://www.cnblogs.com/hugeboke/p/11574924.html