123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308 |
- using Newtonsoft.Json.Linq;
- using System;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.IO;
- using System.Linq;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web;
- using Newtonsoft.Json;
- using System.Net;
- namespace WMS.Util
- {
- public class HttpHelper
- {
- private HttpClient _httpClient;
- private string _baseIPAddress;
- /// <param name="ipaddress">请求的基础IP,例如:http://192.168.0.33:8080/ </param>
- public HttpHelper(string ipaddress = "")
- {
- this._baseIPAddress = ipaddress;
- _httpClient = new HttpClient { BaseAddress = new Uri(_baseIPAddress) };
- }
- /// <summary>
- /// 创建带用户信息的请求客户端
- /// </summary>
- /// <param name="userName">用户账号</param>
- /// <param name="pwd">用户密码,当WebApi端不要求密码验证时,可传空串</param>
- /// <param name="uriString">The URI string.</param>
- public HttpHelper(string userName, string pwd = "", string uriString = "")
- : this(uriString)
- {
- if (!string.IsNullOrEmpty(userName))
- {
- _httpClient.DefaultRequestHeaders.Authorization = CreateBasicCredentials(userName, pwd);
- }
- }
- /// <para>Get请求数据以url参数的方式提交</para>
- /// </summary>
- /// <param name="parameters">参数字典,可为空</param>
- /// <param name="requestUri">例如/api/Files/UploadFile</param>
- /// <returns></returns>
- public string Get(Dictionary<string, string> parameters, string requestUri,string environment= "")
- {
- string strParam = "";
- if (!string.IsNullOrWhiteSpace(environment))
- {
- strParam = "environment=" + environment;
- }
- if (parameters != null)
- {
- strParam += string.Join("&", parameters.Select(o => o.Key + "=" + o.Value)).TrimStart('&');
- }
- if(!string.IsNullOrWhiteSpace(strParam))
- {
- requestUri = string.Concat(ConcatURL(requestUri), '?', strParam);
- }
- else
- {
- requestUri = ConcatURL(requestUri);
- }
- var result = _httpClient.GetStringAsync(requestUri);
- return result.Result;
- }
-
- /// <summary>
- /// Post Dic数据
- /// <para>最终以formurlencode的方式放置在http体中</para>
- /// </summary>
- /// <returns>System.String.</returns>
- public string PostDic(Dictionary<string, string> temp, string requestUri)
- {
- HttpContent httpContent = new FormUrlEncodedContent(temp);
- httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
- return Post(requestUri, httpContent);
- }
- public string PostByte(byte[] bytes, string requestUrl)
- {
- HttpContent content = new ByteArrayContent(bytes);
- content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
- return Post(requestUrl, content);
- }
- public string Post(string requestUrl, HttpContent content)
- {
- var result = _httpClient.PostAsync(ConcatURL(requestUrl), content);
- return result.Result.Content.ReadAsStringAsync().Result;
- }
- /// <summary>
- /// 把请求的URL相对路径组合成绝对路径
- /// </summary>
- private string ConcatURL(string requestUrl)
- {
- return new Uri(_httpClient.BaseAddress, requestUrl).OriginalString;
- }
- private AuthenticationHeaderValue CreateBasicCredentials(string userName, string password)
- {
- string toEncode = userName + ":" + password;
- // The current HTTP specification says characters here are ISO-8859-1.
- // However, the draft specification for the next version of HTTP indicates this encoding is infrequently
- // used in practice and defines behavior only for ASCII.
- Encoding encoding = Encoding.GetEncoding("utf-8");
- byte[] toBase64 = encoding.GetBytes(toEncode);
- string parameter = Convert.ToBase64String(toBase64);
- return new AuthenticationHeaderValue("Basic", parameter);
- }
- /// <summary>
- /// 凭app id 和 app秘钥获取app token
- /// </summary>
- /// <param name="appid"></param>
- /// <param name="appSecret"></param>
- /// <param name="url"></param>
- /// <returns></returns>
- public string GetAppToken(string appid, string appSecret, string requestUri)
- {
- var parameters = new Dictionary<string, string>();
- parameters.Add("appid", appid);
- parameters.Add("appSecret", appSecret);
- var result = Post(ConcatURL(requestUri), new FormUrlEncodedContent(parameters));
- var obj = JObject.Parse(result);
- if (obj["Data"]["tempToken"] == null)
- {
- return null;
- }
- return obj["Data"]["tempToken"].Value<string>();
- }
- /// <summary>
- /// 凭访问授权token获取数据
- /// </summary>
- /// <param name="accessToken">访问授权token</param>
- /// <param name="url">获取授权信息的SSO API地址</param>
- /// <returns></returns>
- public JObject GetMsgWithAccessToken(string accessToken, string requestUrl)
- {
- _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
- var result = _httpClient.GetAsync(ConcatURL(requestUrl));
- return JObject.Parse(result.Result.Content.ReadAsStringAsync().Result);
- }
- public JObject CheckLogin(string accessToken, string requestUrl)
- {
- _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
- var result = _httpClient.GetAsync(ConcatURL(requestUrl));
- return JObject.Parse(result.Result.Content.ReadAsStringAsync().Result);
- }
-
- /// <summary>
- /// 将查询字符串解析转换为名值集合.
- /// </summary>
- /// <param name="queryString"></param>
- /// <returns></returns>
- public static NameValueCollection GetQueryString(string queryString)
- {
- return GetQueryString(queryString, null, true);
- }
- /// <summary>
- /// 将查询字符串解析转换为名值集合.
- /// </summary>
- /// <param name="queryString"></param>
- /// <param name="encoding"></param>
- /// <param name="isEncoded"></param>
- /// <returns></returns>
- public static NameValueCollection GetQueryString(string queryString, Encoding encoding, bool isEncoded)
- {
- queryString = queryString.Replace("?", "");
- NameValueCollection result = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
- if (!string.IsNullOrEmpty(queryString))
- {
- int count = queryString.Length;
- for (int i = 0; i < count; i++)
- {
- int startIndex = i;
- int index = -1;
- while (i < count)
- {
- char item = queryString[i];
- if (item == '=')
- {
- if (index < 0)
- {
- index = i;
- }
- }
- else if (item == '&')
- {
- break;
- }
- i++;
- }
- string key = null;
- string value = null;
- if (index >= 0)
- {
- key = queryString.Substring(startIndex, index - startIndex);
- value = queryString.Substring(index + 1, (i - index) - 1);
- }
- else
- {
- key = queryString.Substring(startIndex, i - startIndex);
- }
- if (isEncoded)
- {
- result[MyUrlDeCode(key, encoding)] = MyUrlDeCode(value, encoding);
- }
- else
- {
- result[key] = value;
- }
- if ((i == (count - 1)) && (queryString[i] == '&'))
- {
- result[key] = string.Empty;
- }
- }
- }
- return result;
- }
- /// <summary>
- /// 解码URL.
- /// </summary>
- /// <param name="encoding">null为自动选择编码</param>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string MyUrlDeCode(string str, Encoding encoding)
- {
- if (encoding == null)
- {
- Encoding utf8 = Encoding.UTF8;
- //首先用utf-8进行解码
- string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
- //将已经解码的字符再次进行编码.
- string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
- if (str == encode)
- encoding = Encoding.UTF8;
- else
- encoding = Encoding.GetEncoding("gb2312");
- }
- return HttpUtility.UrlDecode(str, encoding);
- }
- /// <summary>
- /// Post请求调用
- /// </summary>
- /// <param name="urlPath"></param>
- /// <param name="data">post数据</param>
- /// <returns></returns>
- public string Post(string urlPath, string data, Dictionary<string, string> dictionary)
- {
- //HttpClientHandler handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
- //HttpClient httpClient = new HttpClient(handler);
- //HttpContent是HTTP实体正文和内容标头的基类。
- HttpContent httpContent = new StringContent(data, Encoding.UTF8, "text/json");
- //httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BasicAuth", Ticket);//验证请求头赋值
- foreach(var item in dictionary)
- {
- httpContent.Headers.Add(item.Key, item.Value); //添加自定义请求头
- }
- _httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
- //发送异步Post请求
- HttpResponseMessage response = _httpClient.PostAsync(ConcatURL(urlPath), httpContent).Result;
- // response.EnsureSuccessStatusCode();
- string resultStr = response.Content.ReadAsStringAsync().Result;
- return resultStr;
- }
- public string Post(string parmJosn, string requestUri="", string contentType = "application/json", string charSet = "utf-8")
- {
- HttpContent httpContent = new StringContent(parmJosn);
- httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
- httpContent.Headers.ContentType.CharSet = charSet;
- var resultJson = Post(requestUri, httpContent);
- return resultJson;
- }
- public T Post<T>(string parmJosn, string requestUri = "", string contentType = "application/json", string charSet = "utf-8")
- {
- HttpContent httpContent = new StringContent(parmJosn);
- httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
- httpContent.Headers.ContentType.CharSet = charSet;
- var resultJson = Post(requestUri, httpContent);
- return JsonConvert.DeserializeObject<T>(resultJson);
- }
- }
- public enum SerializableType
- {
- Protobuf,
- Json
- }
- }
|