HttpUtil.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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.Text;
  8. using System.Threading.Tasks;
  9. namespace efunbox_xyyf_windows.util
  10. {
  11. public class HttpUtil
  12. {
  13. public static HttpResult HttpRequest(HttpItem httpItem)
  14. {
  15. HttpResult result = new HttpResult();
  16. try
  17. {
  18. HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(httpItem.Url);
  19. httpWebRequest.Method = httpItem.Method.ToString();
  20. httpWebRequest.Headers = httpItem.Header;
  21. httpWebRequest.ContentType = HttpContentType.APPLICATION_JSON;
  22. httpWebRequest.Timeout = httpItem.TimeOut;
  23. if (httpItem.Method == RequestMethod.POST && (httpItem.RequestValue != null))
  24. {
  25. httpWebRequest.ContentLength = httpItem.RequestValue.Length;
  26. using (Stream requestStream = httpWebRequest.GetRequestStream())
  27. {
  28. requestStream.Write(httpItem.RequestValue, 0, httpItem.RequestValue.Length);
  29. }
  30. }
  31. try
  32. {
  33. //正常情况获取web服务器返回数据
  34. var httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
  35. using (Stream responseStream = httpWebResponse.GetResponseStream())
  36. {
  37. MemoryStream memoryStream = new MemoryStream();
  38. responseStream.CopyTo(memoryStream);
  39. result.HttpByteData = memoryStream.ToArray();
  40. memoryStream.Seek(0, SeekOrigin.Begin);
  41. result.HttpStringData = (httpWebResponse.ContentEncoding != null && httpWebResponse.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase)) ? memoryStream.ReadGzipText(httpItem.Encoding) : memoryStream.ReadText(httpItem.Encoding);
  42. }
  43. }
  44. catch (System.Net.WebException ex)
  45. {
  46. Console.Write(ex.Message);//远程服务器返回错误: (400) 错误的请求。
  47. var strResponse = GetResponseAsString((System.Net.HttpWebResponse)ex.Response, Encoding.UTF8);//这样获取web服务器返回数据
  48. result.HttpStringData = strResponse;
  49. }
  50. return result;
  51. }
  52. catch (Exception ex)
  53. {
  54. result.Status = false;
  55. result.Msg = ex.Message;
  56. return result;
  57. }
  58. }
  59. private static string GetResponseAsString(HttpWebResponse res, Encoding encoding)
  60. {
  61. try
  62. {
  63. StreamReader sr = new StreamReader(res.GetResponseStream(), encoding);
  64. return sr.ReadToEnd();
  65. }
  66. catch (Exception ex)
  67. {
  68. Console.WriteLine(ex.Message);
  69. return "GetResponseAsString catch";
  70. }
  71. }
  72. }
  73. public class HttpItem
  74. {
  75. /// <summary>
  76. /// Url地址
  77. /// </summary>
  78. private string url;
  79. public string Url
  80. {
  81. get
  82. {
  83. if (!url.ToLower().StartsWith("http"))
  84. {
  85. url = "http://" + url;
  86. }
  87. return url;
  88. }
  89. set { url = value; }
  90. }
  91. /// <summary>
  92. /// Method
  93. /// </summary>
  94. public RequestMethod Method { get; set; } = RequestMethod.POST;
  95. /// <summary>
  96. /// 超时时间
  97. /// </summary>
  98. public int TimeOut { get; set; } = 1000 * 60;
  99. /// <summary>
  100. /// 接收的ContentType
  101. /// </summary>
  102. public string ContentType { get; set; } = HttpContentType.APPLICATION_JSON;
  103. /// <summary>
  104. /// 发送的ContentType
  105. /// </summary>
  106. public string HeaderContentType { get; set; } = HttpContentType.APPLICATION_JSON;
  107. /// <summary>
  108. ///
  109. /// </summary>
  110. public string UserAgent { get; set; }
  111. /// <summary>
  112. /// 编码
  113. /// </summary>
  114. public Encoding Encoding { get; set; } = Encoding.UTF8;
  115. /// <summary>
  116. /// 发送的数据类型
  117. /// </summary>
  118. public RequesDataType RequestDataType { get; set; } = RequesDataType.Text;
  119. /// <summary>
  120. /// 发送的数据
  121. /// </summary>
  122. public object RequestData { get; set; }
  123. /// <summary>
  124. /// 根据数据类型转换数据
  125. /// </summary>
  126. public byte[] RequestValue
  127. {
  128. get
  129. {
  130. byte[] bytes = null;
  131. if (RequestData != null)
  132. {
  133. switch (RequestDataType)
  134. {
  135. case RequesDataType.Text:
  136. bytes = Encoding.GetBytes(RequestData.ToString());
  137. //bytes = Encoding.UTF8.GetBytes(RequestData.ToString());
  138. break;
  139. case RequesDataType.StringText:
  140. bytes = Encoding.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(RequestData));
  141. break;
  142. case RequesDataType.Byte:
  143. bytes = RequestData as byte[];
  144. break;
  145. }
  146. }
  147. return bytes;
  148. }
  149. }
  150. private WebHeaderCollection _header;
  151. /// <summary>
  152. /// 设置Header
  153. /// </summary>
  154. public WebHeaderCollection Header
  155. {
  156. get
  157. {
  158. if (_header == null)
  159. {
  160. _header = new WebHeaderCollection();
  161. }
  162. //使用下面语句会出现异常 :error:必须使用适当的属性或方法修改“Content-Type”标头。
  163. //_header.Add(HttpResponseHeader.ContentType, HeaderContentType);
  164. return _header;
  165. }
  166. set { _header = value; }
  167. }
  168. public HttpItem(string url, RequesDataType requestDataType = RequesDataType.Text, object requestData = null)
  169. {
  170. Url = url;
  171. RequestDataType = requestDataType;
  172. RequestData = requestData;
  173. }
  174. }
  175. public class HttpResult
  176. {
  177. public bool Status { get; set; } = true;
  178. public string Msg { get; set; } = "Success";
  179. public string HttpStringData { get; set; }
  180. public byte[] HttpByteData { get; set; }
  181. }
  182. public enum RequestMethod
  183. {
  184. GET, POST
  185. }
  186. public enum RequesDataType
  187. {
  188. Text,
  189. // 如果WebApi设置接收类型为[FromBody]String,需将数据先转义为String
  190. // 如:SendData:"data", 转义:"\"data\""
  191. StringText,
  192. Byte
  193. }
  194. }
  195. /// <summary>
  196. /// Stream扩展类
  197. /// </summary>
  198. public static class StreamEx
  199. {
  200. /// <summary>
  201. /// 流转字符串
  202. /// </summary>
  203. /// <param name="stream"></param>
  204. /// <param name="encoding"></param>
  205. /// <returns></returns>
  206. public static string ReadText(this Stream stream, Encoding encoding)
  207. {
  208. string text = string.Empty;
  209. using (StreamReader streamReader = new StreamReader(stream, encoding))
  210. {
  211. text = streamReader.ReadToEnd();
  212. }
  213. return text;
  214. }
  215. /// <summary>
  216. /// 流转Gzip压缩字符串
  217. /// </summary>
  218. /// <param name="stream"></param>
  219. /// <param name="encoding"></param>
  220. /// <returns></returns>
  221. public static string ReadGzipText(this Stream stream, Encoding encoding)
  222. {
  223. string text = string.Empty;
  224. using (GZipStream gZipStream = new GZipStream(stream, CompressionMode.Decompress))
  225. {
  226. using (StreamReader reader = new StreamReader(gZipStream, encoding))
  227. {
  228. text = reader.ReadToEnd();
  229. }
  230. }
  231. return text;
  232. }
  233. }
  234. /// <summary>
  235. /// HTTP 内容类型(Content-Type)
  236. /// </summary>
  237. public class HttpContentType
  238. {
  239. /// <summary>
  240. /// 资源类型:普通文本
  241. /// </summary>
  242. public const string TEXT_PLAIN = "text/plain";
  243. /// <summary>
  244. /// 资源类型:JSON字符串
  245. /// </summary>
  246. public const string APPLICATION_JSON = "application/json";
  247. /// <summary>
  248. /// 资源类型:未知类型(数据流)
  249. /// </summary>
  250. public const string APPLICATION_OCTET_STREAM = "application/octet-stream";
  251. /// <summary>
  252. /// 资源类型:表单数据(键值对)
  253. /// </summary>
  254. public const string WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
  255. /// <summary>
  256. /// 资源类型:表单数据(键值对)。编码方式为 gb2312
  257. /// </summary>
  258. public const string WWW_FORM_URLENCODED_GB2312 = "application/x-www-form-urlencoded;charset=gb2312";
  259. /// <summary>
  260. /// 资源类型:表单数据(键值对)。编码方式为 utf-8
  261. /// </summary>
  262. public const string WWW_FORM_URLENCODED_UTF8 = "application/x-www-form-urlencoded;charset=utf-8";
  263. /// <summary>
  264. /// 资源类型:多分部数据
  265. /// </summary>
  266. public const string MULTIPART_FORM_DATA = "multipart/form-data";
  267. }