HttpServices.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Web;
  8. using Newtonsoft.Json.Linq;
  9. using Ini;
  10. using FileInfoClass;
  11. using Newtonsoft.Json;
  12. namespace HttpServices
  13. {
  14. public class RestClient
  15. {
  16. FileClass fileclass = new FileClass();
  17. private string logPath = "";
  18. public string HISHTTPServices(string data, string ip = "", string url = "", string authorization = "")
  19. {
  20. IniFile ini = new IniFile();
  21. string hisip = ip;
  22. string hisurl = url;
  23. string hisauthorization = authorization;
  24. if (ip == "")
  25. {
  26. hisip = ini.IniReadValue("HIS", "ip");
  27. }
  28. if (url == "")
  29. {
  30. hisurl = ini.IniReadValue("HIS", "url");
  31. }
  32. if (authorization == "")
  33. {
  34. hisauthorization = ini.IniReadValue("HIS", "authorization");
  35. }
  36. if (hisip.IndexOf(hisurl) > -1) {
  37. hisurl = "";
  38. }
  39. RestClient client = new RestClient();
  40. string result = client.Post(data, hisip, hisurl, hisauthorization);
  41. return result;
  42. }
  43. public string InsuPTHTTPServices(string methodName, string data)
  44. {
  45. IniFile ini = new IniFile();
  46. logPath = ini.IniReadValue("LOG", "path");
  47. fileclass.WriteLogFile(logPath, DateTime.Now.TimeOfDay.ToString() + "-->" + methodName + " in: " + data);
  48. string hisip = ini.IniReadValue("InsuPT", "ip");
  49. string hisurl = ini.IniReadValue("InsuPT", "url");
  50. string hisauthorization = ini.IniReadValue("InsuPT", "authorization");
  51. //fileclass.WriteLogFile(logPath, DateTime.Now.TimeOfDay.ToString() + "-->" + methodName + " url: " + hisip+"/"+ hisurl+" "+ hisauthorization);
  52. RestClient client = new RestClient();
  53. string result = client.Post(data, hisip, hisurl, hisauthorization);
  54. fileclass.WriteLogFile(logPath, DateTime.Now.TimeOfDay.ToString() + "-->" + methodName + " out: " + result);
  55. return result;
  56. }
  57. public string HTTPHeadersServices(string data, string ip, string url, string authorization, string headers)
  58. {
  59. string result = Post(data, ip, url, authorization, headers);
  60. return result;
  61. }
  62. #region Get请求
  63. public string Get(string hisip, string uri)
  64. {
  65. //先根据用户请求的uri构造请求地址
  66. string serviceUrl = string.Format("{0}/{1}", hisip, uri);
  67. //创建Web访问对 象
  68. HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
  69. //通过Web访问对象获取响应内容
  70. HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
  71. //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
  72. StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
  73. //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
  74. string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
  75. reader.Close();
  76. myResponse.Close();
  77. return returnXml;
  78. }
  79. #endregion
  80. #region Post请求
  81. public string Post(string data, string hisip, string hisurl, string hisauthorization, string headers = null)
  82. {
  83. //先根据用户请求的uri构造请求地址
  84. string serviceUrl = string.Format("{0}/{1}", hisip, hisurl);
  85. ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
  86. ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
  87. //创建Web访问对象
  88. HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
  89. //
  90. //把用户传过来的数据转成“UTF-8”的字节流
  91. byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
  92. string returnXml = "";
  93. myRequest.Method = "POST";
  94. myRequest.ContentLength = buf.Length;
  95. myRequest.ContentType = "application/json; charset=utf-8";
  96. myRequest.Accept = "application/json; charset=utf-8";
  97. if (hisauthorization != null)
  98. {
  99. myRequest.Headers.Add("Authorization", hisauthorization);
  100. }
  101. if ((headers != null) && (headers != ""))
  102. {
  103. JObject headersObj = JsonConvert.DeserializeObject<JObject>(headers);
  104. foreach (var header in headersObj)
  105. {
  106. myRequest.Headers.Add(header.Key, header.Value.ToString());
  107. }
  108. }
  109. //myRequest.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
  110. //myRequest.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36");
  111. //myRequest.Headers.Add("Authorization", hisauthorization);
  112. myRequest.MaximumAutomaticRedirections = 1;
  113. myRequest.AllowAutoRedirect = true;
  114. //发送请求
  115. Stream stream = myRequest.GetRequestStream();
  116. stream.Write(buf, 0, buf.Length);
  117. stream.Close();
  118. //获取接口返回值
  119. //通过Web访问对象获取响应内容
  120. // 获取响应并处理
  121. using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
  122. //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
  123. using (Stream responseStream = myResponse.GetResponseStream())
  124. using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
  125. {
  126. returnXml = reader.ReadToEnd();
  127. WebHeaderCollection Headers = myResponse.Headers; // 将响应头赋值给返回对象
  128. string headersInfo = HeadersToJson(Headers);
  129. JObject headersInfoObj = JsonConvert.DeserializeObject<JObject>(headersInfo);
  130. var outlist = new { body = returnXml, headers = headersInfoObj };
  131. returnXml = JsonConvert.SerializeObject(outlist);
  132. }
  133. return returnXml;
  134. }
  135. public static string HeadersToJson(WebHeaderCollection headers)
  136. {
  137. if (headers == null)
  138. return "{}";
  139. var headerDict = new Dictionary<string, string>();
  140. foreach (string key in headers.AllKeys)
  141. {
  142. // 注意:同一个 header 可能有多个值(如 Set-Cookie),这里取第一个或合并
  143. headerDict[key] = headers.Get(key); // Get(key) 返回所有值(逗号分隔)
  144. }
  145. return JsonConvert.SerializeObject(headerDict, Formatting.None);
  146. }
  147. #endregion
  148. }
  149. }