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;
/// 请求的基础IP,例如:http://192.168.0.33:8080/
public HttpHelper(string ipaddress = "")
{
this._baseIPAddress = ipaddress;
_httpClient = new HttpClient { BaseAddress = new Uri(_baseIPAddress) };
}
///
/// 创建带用户信息的请求客户端
///
/// 用户账号
/// 用户密码,当WebApi端不要求密码验证时,可传空串
/// The URI string.
public HttpHelper(string userName, string pwd = "", string uriString = "")
: this(uriString)
{
if (!string.IsNullOrEmpty(userName))
{
_httpClient.DefaultRequestHeaders.Authorization = CreateBasicCredentials(userName, pwd);
}
}
/// Get请求数据以url参数的方式提交
///
/// 参数字典,可为空
/// 例如/api/Files/UploadFile
///
public string Get(Dictionary 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;
}
///
/// Post Dic数据
/// 最终以formurlencode的方式放置在http体中
///
/// System.String.
public string PostDic(Dictionary 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;
}
///
/// 把请求的URL相对路径组合成绝对路径
///
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);
}
///
/// 凭app id 和 app秘钥获取app token
///
///
///
///
///
public string GetAppToken(string appid, string appSecret, string requestUri)
{
var parameters = new Dictionary();
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();
}
///
/// 凭访问授权token获取数据
///
/// 访问授权token
/// 获取授权信息的SSO API地址
///
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);
}
///
/// 将查询字符串解析转换为名值集合.
///
///
///
public static NameValueCollection GetQueryString(string queryString)
{
return GetQueryString(queryString, null, true);
}
///
/// 将查询字符串解析转换为名值集合.
///
///
///
///
///
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;
}
///
/// 解码URL.
///
/// null为自动选择编码
///
///
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);
}
///
/// Post请求调用
///
///
/// post数据
///
public string Post(string urlPath, string data, Dictionary 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(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(resultJson);
}
}
public enum SerializableType
{
Protobuf,
Json
}
}