HttpHelper.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Net.Http.Headers;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using System.Web;
  12. using Newtonsoft.Json;
  13. using System.Net;
  14. namespace WMS.Util
  15. {
  16. public class HttpHelper
  17. {
  18. private HttpClient _httpClient;
  19. private string _baseIPAddress;
  20. /// <param name="ipaddress">请求的基础IP,例如:http://192.168.0.33:8080/ </param>
  21. public HttpHelper(string ipaddress = "")
  22. {
  23. this._baseIPAddress = ipaddress;
  24. _httpClient = new HttpClient { BaseAddress = new Uri(_baseIPAddress) };
  25. }
  26. /// <summary>
  27. /// 创建带用户信息的请求客户端
  28. /// </summary>
  29. /// <param name="userName">用户账号</param>
  30. /// <param name="pwd">用户密码,当WebApi端不要求密码验证时,可传空串</param>
  31. /// <param name="uriString">The URI string.</param>
  32. public HttpHelper(string userName, string pwd = "", string uriString = "")
  33. : this(uriString)
  34. {
  35. if (!string.IsNullOrEmpty(userName))
  36. {
  37. _httpClient.DefaultRequestHeaders.Authorization = CreateBasicCredentials(userName, pwd);
  38. }
  39. }
  40. /// <para>Get请求数据以url参数的方式提交</para>
  41. /// </summary>
  42. /// <param name="parameters">参数字典,可为空</param>
  43. /// <param name="requestUri">例如/api/Files/UploadFile</param>
  44. /// <returns></returns>
  45. public string Get(Dictionary<string, string> parameters, string requestUri,string environment= "")
  46. {
  47. string strParam = "";
  48. if (!string.IsNullOrWhiteSpace(environment))
  49. {
  50. strParam = "environment=" + environment;
  51. }
  52. if (parameters != null)
  53. {
  54. strParam += string.Join("&", parameters.Select(o => o.Key + "=" + o.Value)).TrimStart('&');
  55. }
  56. if(!string.IsNullOrWhiteSpace(strParam))
  57. {
  58. requestUri = string.Concat(ConcatURL(requestUri), '?', strParam);
  59. }
  60. else
  61. {
  62. requestUri = ConcatURL(requestUri);
  63. }
  64. var result = _httpClient.GetStringAsync(requestUri);
  65. return result.Result;
  66. }
  67. /// <summary>
  68. /// Post Dic数据
  69. /// <para>最终以formurlencode的方式放置在http体中</para>
  70. /// </summary>
  71. /// <returns>System.String.</returns>
  72. public string PostDic(Dictionary<string, string> temp, string requestUri)
  73. {
  74. HttpContent httpContent = new FormUrlEncodedContent(temp);
  75. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
  76. return Post(requestUri, httpContent);
  77. }
  78. public string PostByte(byte[] bytes, string requestUrl)
  79. {
  80. HttpContent content = new ByteArrayContent(bytes);
  81. content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
  82. return Post(requestUrl, content);
  83. }
  84. public string Post(string requestUrl, HttpContent content)
  85. {
  86. var result = _httpClient.PostAsync(ConcatURL(requestUrl), content);
  87. return result.Result.Content.ReadAsStringAsync().Result;
  88. }
  89. /// <summary>
  90. /// 把请求的URL相对路径组合成绝对路径
  91. /// </summary>
  92. private string ConcatURL(string requestUrl)
  93. {
  94. return new Uri(_httpClient.BaseAddress, requestUrl).OriginalString;
  95. }
  96. private AuthenticationHeaderValue CreateBasicCredentials(string userName, string password)
  97. {
  98. string toEncode = userName + ":" + password;
  99. // The current HTTP specification says characters here are ISO-8859-1.
  100. // However, the draft specification for the next version of HTTP indicates this encoding is infrequently
  101. // used in practice and defines behavior only for ASCII.
  102. Encoding encoding = Encoding.GetEncoding("utf-8");
  103. byte[] toBase64 = encoding.GetBytes(toEncode);
  104. string parameter = Convert.ToBase64String(toBase64);
  105. return new AuthenticationHeaderValue("Basic", parameter);
  106. }
  107. /// <summary>
  108. /// 凭app id 和 app秘钥获取app token
  109. /// </summary>
  110. /// <param name="appid"></param>
  111. /// <param name="appSecret"></param>
  112. /// <param name="url"></param>
  113. /// <returns></returns>
  114. public string GetAppToken(string appid, string appSecret, string requestUri)
  115. {
  116. var parameters = new Dictionary<string, string>();
  117. parameters.Add("appid", appid);
  118. parameters.Add("appSecret", appSecret);
  119. var result = Post(ConcatURL(requestUri), new FormUrlEncodedContent(parameters));
  120. var obj = JObject.Parse(result);
  121. if (obj["Data"]["tempToken"] == null)
  122. {
  123. return null;
  124. }
  125. return obj["Data"]["tempToken"].Value<string>();
  126. }
  127. /// <summary>
  128. /// 凭访问授权token获取数据
  129. /// </summary>
  130. /// <param name="accessToken">访问授权token</param>
  131. /// <param name="url">获取授权信息的SSO API地址</param>
  132. /// <returns></returns>
  133. public JObject GetMsgWithAccessToken(string accessToken, string requestUrl)
  134. {
  135. _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
  136. var result = _httpClient.GetAsync(ConcatURL(requestUrl));
  137. return JObject.Parse(result.Result.Content.ReadAsStringAsync().Result);
  138. }
  139. public JObject CheckLogin(string accessToken, string requestUrl)
  140. {
  141. _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
  142. var result = _httpClient.GetAsync(ConcatURL(requestUrl));
  143. return JObject.Parse(result.Result.Content.ReadAsStringAsync().Result);
  144. }
  145. /// <summary>
  146. /// 将查询字符串解析转换为名值集合.
  147. /// </summary>
  148. /// <param name="queryString"></param>
  149. /// <returns></returns>
  150. public static NameValueCollection GetQueryString(string queryString)
  151. {
  152. return GetQueryString(queryString, null, true);
  153. }
  154. /// <summary>
  155. /// 将查询字符串解析转换为名值集合.
  156. /// </summary>
  157. /// <param name="queryString"></param>
  158. /// <param name="encoding"></param>
  159. /// <param name="isEncoded"></param>
  160. /// <returns></returns>
  161. public static NameValueCollection GetQueryString(string queryString, Encoding encoding, bool isEncoded)
  162. {
  163. queryString = queryString.Replace("?", "");
  164. NameValueCollection result = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
  165. if (!string.IsNullOrEmpty(queryString))
  166. {
  167. int count = queryString.Length;
  168. for (int i = 0; i < count; i++)
  169. {
  170. int startIndex = i;
  171. int index = -1;
  172. while (i < count)
  173. {
  174. char item = queryString[i];
  175. if (item == '=')
  176. {
  177. if (index < 0)
  178. {
  179. index = i;
  180. }
  181. }
  182. else if (item == '&')
  183. {
  184. break;
  185. }
  186. i++;
  187. }
  188. string key = null;
  189. string value = null;
  190. if (index >= 0)
  191. {
  192. key = queryString.Substring(startIndex, index - startIndex);
  193. value = queryString.Substring(index + 1, (i - index) - 1);
  194. }
  195. else
  196. {
  197. key = queryString.Substring(startIndex, i - startIndex);
  198. }
  199. if (isEncoded)
  200. {
  201. result[MyUrlDeCode(key, encoding)] = MyUrlDeCode(value, encoding);
  202. }
  203. else
  204. {
  205. result[key] = value;
  206. }
  207. if ((i == (count - 1)) && (queryString[i] == '&'))
  208. {
  209. result[key] = string.Empty;
  210. }
  211. }
  212. }
  213. return result;
  214. }
  215. /// <summary>
  216. /// 解码URL.
  217. /// </summary>
  218. /// <param name="encoding">null为自动选择编码</param>
  219. /// <param name="str"></param>
  220. /// <returns></returns>
  221. public static string MyUrlDeCode(string str, Encoding encoding)
  222. {
  223. if (encoding == null)
  224. {
  225. Encoding utf8 = Encoding.UTF8;
  226. //首先用utf-8进行解码
  227. string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
  228. //将已经解码的字符再次进行编码.
  229. string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
  230. if (str == encode)
  231. encoding = Encoding.UTF8;
  232. else
  233. encoding = Encoding.GetEncoding("gb2312");
  234. }
  235. return HttpUtility.UrlDecode(str, encoding);
  236. }
  237. /// <summary>
  238. /// Post请求调用
  239. /// </summary>
  240. /// <param name="urlPath"></param>
  241. /// <param name="data">post数据</param>
  242. /// <returns></returns>
  243. public string Post(string urlPath, string data, Dictionary<string, string> dictionary)
  244. {
  245. //HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
  246. //HttpClient httpClient = new HttpClient(handler);
  247. //HttpContent是HTTP实体正文和内容标头的基类。
  248. HttpContent httpContent = new StringContent(data, Encoding.UTF8, "text/json");
  249. //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BasicAuth", Ticket);//验证请求头赋值
  250. foreach(var item in dictionary)
  251. {
  252. httpContent.Headers.Add(item.Key, item.Value); //添加自定义请求头
  253. }
  254. _httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
  255. //发送异步Post请求
  256. HttpResponseMessage response = _httpClient.PostAsync(ConcatURL(urlPath), httpContent).Result;
  257. // response.EnsureSuccessStatusCode();
  258. string resultStr = response.Content.ReadAsStringAsync().Result;
  259. return resultStr;
  260. }
  261. public string Post(string parmJosn, string requestUri="", string contentType = "application/json", string charSet = "utf-8")
  262. {
  263. HttpContent httpContent = new StringContent(parmJosn);
  264. httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
  265. httpContent.Headers.ContentType.CharSet = charSet;
  266. var resultJson = Post(requestUri, httpContent);
  267. return resultJson;
  268. }
  269. public T Post<T>(string parmJosn, string requestUri = "", string contentType = "application/json", string charSet = "utf-8")
  270. {
  271. HttpContent httpContent = new StringContent(parmJosn);
  272. httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
  273. httpContent.Headers.ContentType.CharSet = charSet;
  274. var resultJson = Post(requestUri, httpContent);
  275. return JsonConvert.DeserializeObject<T>(resultJson);
  276. }
  277. }
  278. public enum SerializableType
  279. {
  280. Protobuf,
  281. Json
  282. }
  283. }