HttpClien Get&Post
阿新 • • 發佈:2017-06-01
tasks class msg 開源 技術 技術分享 threading nuget response
新公司上班第二周,開始進軍.Net Core,這方面的東西比較新,所以已經封裝好的東西比較少,比如HttpClien之類的開源類庫,找了NuGet好久,沒有找到,所以先寫個簡陋的來用著先。
引用: using System.Threading.Tasks; using System.Net.Http; using Newtonsoft.Json; using System.Net.Http.Headers; 幫助類: public static class HttpHelper { public static async Task<T> Get<T>(stringurl) { try { using (var client = new HttpClient()) { var responseMsg = await client.GetAsync(url); if (responseMsg.IsSuccessStatusCode) { string strJson = awaitresponseMsg.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<T>(strJson); } else { return default(T); } } }catch { return default(T); } } public static async Task<T> Post<T>(string url, dynamic para) { try { if (para != null) { var requestJson = JsonConvert.SerializeObject(para); HttpContent httpContent = new StringContent(requestJson); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); using (var client = new HttpClient()) { var responseJson = await client.PostAsync(url, httpContent).Result.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<T>(responseJson); } } return default(T); } catch { return default(T); } } }
調用測試:
//======================================================= // .----. // _.‘__ `. // .--(^)(^^)---/#\ // .‘ @ /###\ // : , ##### // `-..__.-‘ _.-\###/ // `;_: `"‘ // .‘"""""`. // /, ya ,\\ // //向上吧!409 \\ // `-._______.-‘ // ___`. | .‘___ // (______|______) //=======================================================HttpClien Get&Post