时间: 2016/10/30 13:04:07
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Runtime.Serialization.Json; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Platform.Facilitys { public static class HttpHelper { static readonly HttpClient _client; static HttpHelper() { _client = new HttpClient(); } public static TOut PostSync(ApiHost host, TIn postData) where TIn : class where TOut : class { var uri = new Uri(host.Domain); var url = new Uri(uri, host.ApiName); var response = _client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(postData),Encoding.UTF8,host.DataMimeType)).Result; response.EnsureSuccessStatusCode(); return response.Content.DesObj (); } public static Task PostAsync (ApiHost host, TIn postData) where TIn : class where TOut : class { var uri = new Uri(host.Domain); var url = new Uri(uri, host.ApiName); return _client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(postData), Encoding.UTF8, host.DataMimeType)).GetResult (); } public static Task GetAsync (ApiHost host) where TOut : class { var uri = new Uri(host.Domain); var url = new Uri(uri, host.ApiName); return _client.GetAsync(url).GetResult (); } static Task GetResult (this Task tsk) where TOut : class { return tsk.ContinueWith( res => { return res .Result .EnsureSuccessStatusCode() .Content .DesObj (); }, TaskContinuationOptions.OnlyOnRanToCompletion); } static TOut DesObj (this HttpContent content) where TOut : class { var strJson = content.ReadAsStringAsync().Result; if (!string.IsNullOrWhiteSpace(strJson)) { if (strJson.IndexOf("k__BackingField") > 0) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(TOut)); using (var mStream = new MemoryStream(Encoding.Default.GetBytes(strJson))) { return ser.ReadObject(mStream) as TOut; } } else { return JsonConvert.DeserializeObject (strJson); } } return default(TOut); } } /// /// WebApi配置 /// public class ApiHost { #region public ApiHost() { DataMimeType = "application/json"; } public ApiHost(string domain, string apiName, string inputQueryString, string dataMimeType) { Domain = domain; ApiName = apiName; InputQueryString = inputQueryString; DataMimeType = dataMimeType; } #endregion #region /// /// 主域名(比如http://api.rongzi.com or http://127.0.0.1) /// public string Domain { get; set; } /// /// Api名称(api/v1/studentinfotest) /// public string ApiName { get; set; } /// /// 传入参数名称 /// public string InputQueryString { get; set; } /// /// 返回数据类型 /// public string DataMimeType { get; set; } /// /// 重写ToString() /// /// public override string ToString() { return string.Format("{0}|{1}|{2}|{3}", this.ApiName, this.Domain, this.DataMimeType, this.InputQueryString); } #endregion } }