纽威
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

485 lines
18 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Security;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace ICSSoft.Common
  10. {
  11. public class HTTPHelper
  12. {
  13. private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  14. public static string HttpPost(string apiName, string url, string body)
  15. {
  16. try
  17. {
  18. //log.Debug(url + Environment.NewLine + body);
  19. Encoding encoding = Encoding.UTF8;
  20. System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
  21. request.Method = "POST";
  22. request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
  23. request.ContentType = "application/json; charset=utf-8";
  24. // request.ContentType = "text/html, application/xhtml+xml";
  25. byte[] buffer = encoding.GetBytes(body);
  26. request.ContentLength = buffer.Length;
  27. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  28. System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
  29. using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
  30. {
  31. return reader.ReadToEnd();
  32. }
  33. }
  34. catch (System.Net.WebException ex)
  35. {
  36. log.Error(ex.ToString() + Environment.NewLine + url + Environment.NewLine + body);
  37. throw new Exception(apiName + "调用失败," + ex.Message);
  38. }
  39. }
  40. public static string HttpPost(string url, string body)
  41. {
  42. try
  43. {
  44. Encoding encoding = Encoding.UTF8;
  45. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  46. request.Method = "POST";
  47. request.Accept = "text/html, application/xhtml+xml, */*";
  48. request.ContentLength = 110;
  49. request.ContentType = "application/json";
  50. byte[] buffer = encoding.GetBytes(body);
  51. request.ContentLength = buffer.Length;
  52. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  53. log.Error(url + body);
  54. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  55. using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
  56. {
  57. return reader.ReadToEnd();
  58. }
  59. }
  60. catch (WebException ex)
  61. {
  62. var res = (HttpWebResponse)ex.Response;
  63. StringBuilder sb = new StringBuilder();
  64. StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
  65. sb.Append(sr.ReadToEnd());
  66. //string ssb = sb.ToString();
  67. //throw new Exception(sb.ToString());
  68. return "";
  69. }
  70. }
  71. /// <summary>
  72. /// 通过web api获取数据的方法
  73. /// </summary>
  74. /// <param name="url">api的url</param>
  75. /// <param name="method">请求类型,默认是get</param>
  76. /// <param name="postData">post请求所携带的数据</param>
  77. /// <returns></returns>
  78. public static string RequestData(string url, string method, string postData)
  79. {
  80. try
  81. {
  82. log.Error(postData);
  83. method = method.ToUpper();
  84. //设置安全通信协议 我方公司服务器有些强制使用tls1.2的安全通信协议,所以至少包含SecurityProtocolType.Tls12 如果沒有SecurityProtocolType.Tls12设置会报错:HttpWebRequest底层连接已关闭:传送时发生意外错误
  85. ServicePointManager.SecurityProtocol =
  86. SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls |
  87. SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
  88. //创建请求实例
  89. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  90. //设置请求类型
  91. request.Method = method;
  92. //设置请求消息主体的编码方法
  93. request.ContentType = "application/json";
  94. //POST方式處理
  95. if (method == "POST")
  96. {
  97. //用UTF8字符集对post请求携带的数据进行编码,可防止中文乱码
  98. byte[] byteArray = Encoding.UTF8.GetBytes(postData);
  99. //指定客户端post请求携带的数据的长度
  100. request.ContentLength = byteArray.Length;
  101. //创建一个tream,用于写入post请求所携带的数据(该数据写入了请求体)
  102. Stream stream = request.GetRequestStream();
  103. stream.Write(byteArray, 0, byteArray.Length);
  104. stream.Close();
  105. }
  106. //获取请求的响应实例
  107. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  108. //获取读取流实体,用来以UTF8字符集读取响应流中的数据
  109. StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  110. //进行数据读取
  111. string retString = myStreamReader.ReadToEnd();
  112. myStreamReader.Close();
  113. return retString;
  114. }
  115. catch (Exception ex)
  116. {
  117. //拋出異常
  118. throw ex;
  119. }
  120. }
  121. public static string WorkDayPostData(string URL, string JsonData, string ContentType)
  122. {
  123. string str = string.Empty;
  124. try
  125. {
  126. WebRequest request = WebRequest.Create(URL);
  127. request.Method = "POST";
  128. byte[] bytes = System.Text.Encoding.UTF8.GetBytes(JsonData);
  129. request.ContentType = ContentType;
  130. request.ContentLength = bytes.Length;
  131. using (Stream postStream = request.GetRequestStream())
  132. {
  133. postStream.Write(bytes, 0, bytes.Length);
  134. }
  135. request.Credentials = CredentialCache.DefaultCredentials;
  136. WebResponse response = null;
  137. try
  138. {
  139. response = request.GetResponse();
  140. }
  141. catch (WebException ex)
  142. {
  143. if (ex.Status == WebExceptionStatus.ProtocolError)
  144. response = (WebResponse)ex.Response;
  145. }
  146. if (response != null)
  147. {
  148. using (StreamReader st = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
  149. {
  150. str = System.Web.HttpUtility.UrlDecode(st.ReadToEnd());
  151. }
  152. }
  153. }
  154. catch (Exception ex)
  155. {
  156. str = ex.Message;
  157. }
  158. return str;
  159. }
  160. public static void CreateObject(string URL, string DATA)
  161. {
  162. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
  163. request.Method = "POST";
  164. request.ContentType = "application/json";
  165. request.ContentLength = DATA.Length;
  166. StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
  167. requestWriter.Write(DATA);
  168. requestWriter.Close();
  169. try
  170. {
  171. WebResponse webResponse = request.GetResponse();
  172. Stream webStream = webResponse.GetResponseStream();
  173. StreamReader responseReader = new StreamReader(webStream);
  174. string response = responseReader.ReadToEnd();
  175. Console.Out.WriteLine(response);
  176. responseReader.Close();
  177. }
  178. catch (Exception e)
  179. {
  180. Console.Out.WriteLine("-----------------");
  181. Console.Out.WriteLine(e.Message);
  182. }
  183. }
  184. public static string Post(string posturl, string jsonstr)
  185. {
  186. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(posturl);
  187. request.Method = "POST";
  188. request.ContentType = "application/x-www-form-urlencoded";
  189. //json字符串转为字节数组
  190. byte[] bytes = System.Text.Encoding.UTF8.GetBytes(jsonstr);
  191. //设置请求的ContentLength
  192. request.ContentLength = bytes.Length;
  193. //发送请求,获得请求流
  194. Stream stream;
  195. try
  196. {
  197. //获取用于写入请求数据的Stream对象
  198. stream = request.GetRequestStream();
  199. }
  200. catch (Exception ex)
  201. {
  202. stream = null;
  203. Console.WriteLine(ex.Message);
  204. }
  205. //把数据写入流
  206. stream.Write(bytes, 0, bytes.Length);
  207. stream.Close();
  208. HttpWebResponse response;
  209. try
  210. {
  211. //获得响应流
  212. response = (HttpWebResponse)request.GetResponse();
  213. }
  214. catch (WebException ex)
  215. {
  216. response = ex.Response as HttpWebResponse;
  217. }
  218. Stream s = response.GetResponseStream();
  219. StreamReader sr = new StreamReader(s, Encoding.UTF8);
  220. string strVal = sr.ReadToEnd().Trim();
  221. sr.Close();
  222. s.Close();
  223. return strVal;
  224. }
  225. /// <summary>
  226. /// HTTP访问method 常用的几样
  227. /// </summary>
  228. public enum HttpVerb
  229. {
  230. /// <summary>
  231. /// get:获取
  232. /// </summary>
  233. GET,
  234. /// <summary>
  235. /// post:修改
  236. /// </summary>
  237. POST,
  238. /// <summary>
  239. /// put:写入
  240. /// </summary>
  241. PUT,
  242. /// <summary>
  243. /// delete:删除
  244. /// </summary>
  245. DELETE
  246. }
  247. /// <summary>
  248. /// HTTP访问格式类型,根据Postman整理
  249. /// </summary>
  250. public enum HttpContentType
  251. {
  252. /// <summary>
  253. /// text/plain
  254. /// </summary>
  255. Text,
  256. /// <summary>
  257. /// application/json
  258. /// </summary>
  259. JSON,
  260. /// <summary>
  261. /// application/xml
  262. /// </summary>
  263. XML,
  264. /// <summary>
  265. /// text/xml
  266. /// </summary>
  267. TextXML,
  268. /// <summary>
  269. /// text/html
  270. /// </summary>
  271. HTML,
  272. /// <summary>
  273. /// application/javascript
  274. /// </summary>
  275. Javascript
  276. }
  277. /// <summary>
  278. /// Rest方式访问方法,ContentType为application/json
  279. /// </summary>
  280. public class RestHelper
  281. {
  282. /// <summary>
  283. /// 请求的url地址
  284. /// </summary>
  285. public string EndPoint { get; set; }
  286. /// <summary>
  287. /// 请求的方法,默认 GET
  288. /// </summary>
  289. public HttpVerb Method { get; set; }
  290. /// <summary>
  291. /// 格式类型:默认application/json
  292. /// </summary>
  293. public HttpContentType ContentType { get; set; }
  294. /// <summary>
  295. /// 传送的数据,如json字符串
  296. /// </summary>
  297. public string PostData { get; set; }
  298. /// <summary>
  299. /// 编码规范,默认 UTF8
  300. /// </summary>
  301. public Encoding HttpEncoding { get; set; }
  302. /// <summary>
  303. /// 构造函数
  304. /// </summary>
  305. public RestHelper(HttpContentType contentType = HttpContentType.JSON)
  306. {
  307. EndPoint = "";
  308. Method = HttpVerb.GET;
  309. ContentType = contentType;
  310. PostData = "";
  311. HttpEncoding = Encoding.UTF8;
  312. }
  313. /// <summary>
  314. /// 构造函数
  315. /// </summary>
  316. public RestHelper(string endpoint, HttpContentType contentType = HttpContentType.JSON)
  317. {
  318. EndPoint = endpoint;
  319. Method = HttpVerb.GET;
  320. ContentType = contentType;
  321. PostData = "";
  322. HttpEncoding = Encoding.UTF8;
  323. }
  324. /// <summary>
  325. /// 构造函数
  326. /// </summary>
  327. public RestHelper(string endpoint, HttpVerb method, HttpContentType contentType = HttpContentType.JSON)
  328. {
  329. EndPoint = endpoint;
  330. Method = method;
  331. ContentType = contentType;
  332. PostData = "";
  333. HttpEncoding = Encoding.UTF8;
  334. }
  335. /// <summary>
  336. /// 构造函数
  337. /// </summary>
  338. public RestHelper(string endpoint, HttpVerb method, string postData, HttpContentType contentType = HttpContentType.JSON)
  339. {
  340. EndPoint = endpoint;
  341. Method = method;
  342. ContentType = contentType;
  343. PostData = postData;
  344. HttpEncoding = Encoding.UTF8;
  345. }
  346. /// <summary>
  347. /// 构造函数
  348. /// </summary>
  349. public RestHelper(string endpoint, Encoding encoding, HttpVerb method = HttpVerb.GET, string postData = "", HttpContentType contentType = HttpContentType.JSON)
  350. {
  351. EndPoint = endpoint;
  352. Method = method;
  353. ContentType = contentType;
  354. PostData = postData;
  355. HttpEncoding = encoding;
  356. }
  357. /// <summary>
  358. /// 直接访问
  359. /// </summary>
  360. /// <returns></returns>
  361. public string MakeRequest()
  362. {
  363. return MakeRequest("");
  364. }
  365. /// <summary>
  366. /// 带参数访问,如 MakeRequest("?param=0")
  367. /// </summary>
  368. /// <param name="parameters"></param>
  369. /// <returns></returns>
  370. public string MakeRequest(string parameters)
  371. {
  372. try
  373. {
  374. var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
  375. request.Method = Method.ToString();
  376. request.ContentLength = 0;
  377. request.ContentType = GetContentType(ContentType);
  378. //如果传送的数据不为空,并且方法是post或put
  379. if (!string.IsNullOrEmpty(PostData) && (Method == HttpVerb.POST || Method == HttpVerb.PUT))
  380. {
  381. var bytes = HttpEncoding.GetBytes(PostData);//编码方式,默认UTF-8
  382. request.ContentLength = bytes.Length;
  383. using (var writeStream = request.GetRequestStream())
  384. {
  385. writeStream.Write(bytes, 0, bytes.Length);
  386. }
  387. }
  388. using (var response = (HttpWebResponse)request.GetResponse())
  389. {
  390. var responseValue = string.Empty;
  391. if (response.StatusCode != HttpStatusCode.OK)
  392. {
  393. var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
  394. throw new ApplicationException(message);
  395. }
  396. // grab the response
  397. using (var responseStream = response.GetResponseStream())
  398. {
  399. if (responseStream != null)
  400. {
  401. using (var reader = new StreamReader(responseStream))
  402. {
  403. responseValue = reader.ReadToEnd();
  404. }
  405. }
  406. }
  407. return responseValue;
  408. }
  409. }
  410. catch (Exception e)
  411. {
  412. throw new Exception(e.Message);
  413. }
  414. }
  415. /// <summary>
  416. /// 将content type转成字符串描述
  417. /// </summary>
  418. /// <param name="contentType"></param>
  419. /// <returns></returns>
  420. private string GetContentType(HttpContentType contentType)
  421. {
  422. switch (contentType)
  423. {
  424. case HttpContentType.Text:
  425. return "text/plain";
  426. case HttpContentType.JSON:
  427. return "application/json";
  428. case HttpContentType.XML:
  429. return "application/xml";
  430. case HttpContentType.TextXML:
  431. return "text/xml";
  432. case HttpContentType.HTML:
  433. return "text/html";
  434. case HttpContentType.Javascript:
  435. return "application/javascript";
  436. default:
  437. return "";
  438. }
  439. }
  440. }
  441. }
  442. }