HttpClient.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using Bowin.Common.JSON;
  2. using Newtonsoft.Json.Linq;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Text;
  10. namespace Bowin.Common
  11. {
  12. public class HttpClient
  13. {
  14. #region //字段
  15. private ArrayList bytesArray;
  16. private Encoding encoding = Encoding.UTF8;
  17. private string boundary = String.Empty;
  18. private WebHeaderCollection headers = new WebHeaderCollection();
  19. #endregion
  20. #region //构造方法
  21. public HttpClient()
  22. {
  23. bytesArray = new ArrayList();
  24. string flag = DateTime.Now.Ticks.ToString("x");
  25. boundary = "---------------------------" + flag;
  26. headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
  27. }
  28. #endregion
  29. #region //方法
  30. /// <summary>
  31. /// 合并请求数据
  32. /// </summary>
  33. /// <returns></returns>
  34. private byte[] MergeContent()
  35. {
  36. int length = 0;
  37. int readLength = 0;
  38. string endBoundary = "--" + boundary + "--\r\n";
  39. byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);
  40. bytesArray.Add(endBoundaryBytes);
  41. foreach (byte[] b in bytesArray)
  42. {
  43. length += b.Length;
  44. }
  45. byte[] bytes = new byte[length];
  46. foreach (byte[] b in bytesArray)
  47. {
  48. b.CopyTo(bytes, readLength);
  49. readLength += b.Length;
  50. }
  51. return bytes;
  52. }
  53. public bool Download(String requestUrl, Dictionary<string, string> parameters, out String responseText)
  54. {
  55. WebClient webClient = new WebClient();
  56. if (this.headers != null && this.headers.Count > 0)
  57. {
  58. webClient.Headers = this.headers;
  59. }
  60. string fullUrl = requestUrl;
  61. for (int i = 0; i < parameters.Count; i++)
  62. {
  63. if (i == 0 && !requestUrl.Contains("?"))
  64. {
  65. fullUrl += "?";
  66. }
  67. else
  68. {
  69. fullUrl += "&";
  70. }
  71. fullUrl += parameters.Keys.ElementAt(i) + "=" + parameters.Values.ElementAt(i);
  72. }
  73. var response = new byte[0];
  74. try
  75. {
  76. response = webClient.DownloadData(fullUrl);
  77. responseText = System.Text.Encoding.UTF8.GetString(response);
  78. return true;
  79. }
  80. catch (WebException ex)
  81. {
  82. Stream responseStream = ex.Response.GetResponseStream();
  83. response = new byte[ex.Response.ContentLength];
  84. responseStream.Read(response, 0, response.Length);
  85. }
  86. responseText = System.Text.Encoding.UTF8.GetString(response);
  87. return false;
  88. }
  89. /// <summary>
  90. /// 上传
  91. /// </summary>
  92. /// <param name="requestUrl">请求url</param>
  93. /// <param name="responseText">响应</param>
  94. /// <returns></returns>
  95. public bool Upload(String requestUrl, out String responseText)
  96. {
  97. WebClient webClient = new WebClient();
  98. if (this.headers != null && this.headers.Count > 0)
  99. {
  100. webClient.Headers = this.headers;
  101. var contentType = webClient.Headers.AllKeys.Where(x => x.ToLower() == "content-type").Select(x => webClient.Headers[x]).FirstOrDefault();
  102. if (contentType != null)
  103. {
  104. if (!contentType.TrimEnd().EndsWith(";"))
  105. {
  106. contentType += ";";
  107. }
  108. contentType += "boundary=" + boundary;
  109. webClient.Headers.Set("Content-Type", contentType);
  110. }
  111. else
  112. {
  113. webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
  114. }
  115. }
  116. byte[] responseBytes;
  117. byte[] bytes = MergeContent();
  118. try
  119. {
  120. responseBytes = webClient.UploadData(requestUrl, bytes);
  121. responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
  122. return true;
  123. }
  124. catch (WebException ex)
  125. {
  126. Stream responseStream = ex.Response.GetResponseStream();
  127. responseBytes = new byte[ex.Response.ContentLength];
  128. responseStream.Read(responseBytes, 0, responseBytes.Length);
  129. }
  130. responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
  131. return false;
  132. }
  133. public void SetHeaders(WebHeaderCollection headers)
  134. {
  135. if (this.headers != null && headers != null && headers.Count > 0)
  136. {
  137. this.headers = headers;
  138. }
  139. }
  140. /// <summary>
  141. /// 设置表单数据字段
  142. /// </summary>
  143. /// <param name="fieldName">字段名</param>
  144. /// <param name="fieldValue">字段值</param>
  145. /// <returns></returns>
  146. public void SetFieldValue(String fieldName, String fieldValue)
  147. {
  148. string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
  149. string httpRowData = String.Format(httpRow, fieldName, fieldValue);
  150. bytesArray.Add(encoding.GetBytes(httpRowData));
  151. }
  152. /// <summary>
  153. /// 设置表单文件数据
  154. /// </summary>
  155. /// <param name="fieldName">字段名</param>
  156. /// <param name="filename">字段值</param>
  157. /// <param name="contentType">内容内型</param>
  158. /// <param name="fileBytes">文件字节流</param>
  159. /// <returns></returns>
  160. public void SetFieldValue(FormFile formFile)
  161. {
  162. string end = "\r\n";
  163. string httpRow = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
  164. string httpRowData = String.Format(httpRow, formFile.FieldName, formFile.Filename, formFile.ContentType);
  165. byte[] headerBytes = encoding.GetBytes(httpRowData);
  166. byte[] endBytes = encoding.GetBytes(end);
  167. byte[] fileDataBytes = new byte[headerBytes.Length + formFile.FileBytes.Length + endBytes.Length];
  168. headerBytes.CopyTo(fileDataBytes, 0);
  169. formFile.FileBytes.CopyTo(fileDataBytes, headerBytes.Length);
  170. endBytes.CopyTo(fileDataBytes, headerBytes.Length + formFile.FileBytes.Length);
  171. bytesArray.Add(fileDataBytes);
  172. }
  173. #endregion
  174. public static Dictionary<string, string> GetFromCollections<T>(T source) where T : class
  175. {
  176. JObject sourceObj = source.ToJson().ToObject<JObject>();
  177. Dictionary<string, string> result = new Dictionary<string, string>();
  178. foreach (var key in sourceObj.Properties())
  179. {
  180. result.Add(key.Name, key.Value.Value<string>());
  181. }
  182. return result;
  183. }
  184. }
  185. public class FormFile
  186. {
  187. public string FieldName { get; set; }
  188. public string Filename { get; set; }
  189. public string ContentType { get; set; }
  190. public Byte[] FileBytes { get; set; }
  191. }
  192. }