日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > C# >内容正文

C#

c#使用HttpClient调用WebApi

發(fā)布時間:2023/12/18 C# 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c#使用HttpClient调用WebApi 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

調(diào)用WebApi

可以利用HttpClient來進(jìn)行Web Api的調(diào)用。由于WebA Api的調(diào)用本質(zhì)上就是一次普通的發(fā)送請求與接收響應(yīng)的過程,

所有HttpClient其實可以作為一般意義上發(fā)送HTTP請求的工具。

using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks;namespace 自己的名稱空間 {public class ApiHelper{/// <summary>/// api調(diào)用方法/注意一下API地址/// </summary>/// <param name="controllerName">控制器名稱--自己所需調(diào)用的控制器名稱</param>/// <param name="overb">請求方式--get-post-delete-put</param>/// <param name="action">方法名稱--如需一個Id(方法名/ID)(方法名/?ID)根據(jù)你的API靈活運(yùn)用</param>/// <param name="obj">方法參數(shù)--如提交操作傳整個對象</param>/// <returns>json字符串--可以反序列化成你想要的</returns>public static string GetApiMethod(string controllerName, string overb, string action, object obj = null){Task<HttpResponseMessage> task = null;string json = "";HttpClient client = new HttpClient();client.BaseAddress = new Uri("http://localhost:****/api/" + controllerName + "/");switch (overb){case "get":task = client.GetAsync(action);break;case "post":task = client.PostAsJsonAsync(action, obj);break;case "delete":task = client.DeleteAsync(action);break;case "put":task = client.PutAsJsonAsync(action, obj);break;default:break;}task.Wait();var response = task.Result;if (response.IsSuccessStatusCode){var read = response.Content.ReadAsStringAsync();read.Wait();json = read.Result;}return json;}} }

可能需要以下引用集:

System.Net.Http.Formatting.dll

System.Web.Http.dll

*************************************************

C# HttpClient請求Webapi幫助類

引用?Newtonsoft.Json??

// Post請求public string PostResponse(string url,string postData,out string statusCode){string result = string.Empty;//設(shè)置Http的正文HttpContent httpContent = new StringContent(postData);//設(shè)置Http的內(nèi)容標(biāo)頭httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");//設(shè)置Http的內(nèi)容標(biāo)頭的字符httpContent.Headers.ContentType.CharSet = "utf-8";using(HttpClient httpClient=new HttpClient()){//異步PostHttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;//輸出Http響應(yīng)狀態(tài)碼statusCode = response.StatusCode.ToString();//確保Http響應(yīng)成功if (response.IsSuccessStatusCode){//異步讀取jsonresult = response.Content.ReadAsStringAsync().Result;}}return result;}// 泛型:Post請求public T PostResponse<T>(string url,string postData) where T:class,new(){T result = default(T);HttpContent httpContent = new StringContent(postData);httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");httpContent.Headers.ContentType.CharSet = "utf-8";using(HttpClient httpClient=new HttpClient()){HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;if (response.IsSuccessStatusCode){Task<string> t = response.Content.ReadAsStringAsync();string s = t.Result;//Newtonsoft.Jsonstring json = JsonConvert.DeserializeObject(s).ToString();result = JsonConvert.DeserializeObject<T>(json); }}return result;}// 泛型:Get請求public T GetResponse<T>(string url) where T :class,new(){T result = default(T);using (HttpClient httpClient=new HttpClient()){httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));HttpResponseMessage response = httpClient.GetAsync(url).Result;if (response.IsSuccessStatusCode){Task<string> t = response.Content.ReadAsStringAsync();string s = t.Result;string json = JsonConvert.DeserializeObject(s).ToString();result = JsonConvert.DeserializeObject<T>(json);}}return result;}// Get請求public string GetResponse(string url, out string statusCode){string result = string.Empty;using (HttpClient httpClient = new HttpClient()){httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));HttpResponseMessage response = httpClient.GetAsync(url).Result;statusCode = response.StatusCode.ToString();if (response.IsSuccessStatusCode){result = response.Content.ReadAsStringAsync().Result;}}return result;}// Put請求public string PutResponse(string url, string putData, out string statusCode){string result = string.Empty;HttpContent httpContent = new StringContent(putData);httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");httpContent.Headers.ContentType.CharSet = "utf-8";using (HttpClient httpClient = new HttpClient()){HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;statusCode = response.StatusCode.ToString();if (response.IsSuccessStatusCode){result = response.Content.ReadAsStringAsync().Result;}}return result;}// 泛型:Put請求public T PutResponse<T>(string url, string putData) where T : class, new(){T result = default(T);HttpContent httpContent = new StringContent(putData);httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");httpContent.Headers.ContentType.CharSet = "utf-8";using(HttpClient httpClient=new HttpClient()){HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;if (response.IsSuccessStatusCode){Task<string> t = response.Content.ReadAsStringAsync();string s = t.Result;string json = JsonConvert.DeserializeObject(s).ToString();result = JsonConvert.DeserializeObject<T>(json);}}return result;}

?

出處:https://blog.csdn.net/sun_zeliang/article/details/81587835

========================================================

我自己把上面的修改下,可以不引用?Newtonsoft.Json? ,在POST模式的方法PostWebAPI增加了GZip的支持,請求超時設(shè)置,其他的功能可以自己去擴(kuò)展,增加了簡單調(diào)用的方式。

后續(xù)可以擴(kuò)展異步方式、HttpWebRequest方式調(diào)用Webapi(待完成。。。)

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization;namespace Car.AutoUpdate.Comm {public class WebapiHelper{#region HttpClient/// <summary>/// Get請求指定的URL地址/// </summary>/// <param name="url">URL地址</param>/// <returns></returns>public static string GetWebAPI(string url){string result = "";string strOut = "";try{result = GetWebAPI(url, out strOut);}catch (Exception ex){LogHelper.Error("調(diào)用后臺服務(wù)出現(xiàn)異常!", ex);}return result;}/// <summary>/// Get請求指定的URL地址/// </summary>/// <param name="url">URL地址</param>/// <param name="statusCode">Response返回的狀態(tài)</param>/// <returns></returns>public static string GetWebAPI(string url, out string statusCode){string result = string.Empty;statusCode = string.Empty;try{using (HttpClient httpClient = new HttpClient()){httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));HttpResponseMessage response = httpClient.GetAsync(url).Result;statusCode = response.StatusCode.ToString();if (response.IsSuccessStatusCode){result = response.Content.ReadAsStringAsync().Result;}else{LogHelper.Warn("調(diào)用后臺服務(wù)返回失敗:" + url + Environment.NewLine + SerializeObject(response));}}}catch (Exception ex){LogHelper.Error("調(diào)用后臺服務(wù)出現(xiàn)異常!", ex);}return result;}/// <summary>/// Get請求指定的URL地址/// </summary>/// <typeparam name="T">返回的json轉(zhuǎn)換成指定實體對象</typeparam>/// <param name="url">URL地址</param>/// <returns></returns>public static T GetWebAPI<T>(string url) where T : class, new(){T result = default(T);try{using (HttpClient httpClient = new HttpClient()){httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));HttpResponseMessage response = httpClient.GetAsync(url).Result;if (response.IsSuccessStatusCode){Task<string> t = response.Content.ReadAsStringAsync();string s = t.Result;string jsonNamespace = DeserializeObject<T>(s).ToString();result = DeserializeObject<T>(s);}else{LogHelper.Warn("調(diào)用后臺服務(wù)返回失敗:" + url + Environment.NewLine + SerializeObject(response));}}}catch (Exception ex){LogHelper.Error("調(diào)用后臺服務(wù)出現(xiàn)異常!", ex);}return result;}/// <summary>/// Post請求指定的URL地址/// </summary>/// <param name="url">URL地址</param>/// <param name="postData">提交到Web的Json格式的數(shù)據(jù):如:{"ErrCode":"FileErr"}</param>/// <returns></returns>public static string PostWebAPI(string url, string postData){string result = "";HttpStatusCode strOut = HttpStatusCode.BadRequest;try{result = PostWebAPI(url, postData, out strOut);}catch (Exception ex){LogHelper.Error("調(diào)用后臺服務(wù)出現(xiàn)異常!", ex);}return result;}/// <summary>/// Post請求指定的URL地址/// </summary>/// <param name="url">URL地址</param>/// <param name="postData">提交到Web的Json格式的數(shù)據(jù):如:{"ErrCode":"FileErr"}</param>/// <param name="statusCode">Response返回的狀態(tài)</param>/// <returns></returns>public static string PostWebAPI(string url, string postData, out HttpStatusCode httpStatusCode){string result = string.Empty;httpStatusCode = HttpStatusCode.BadRequest;//設(shè)置Http的正文HttpContent httpContent = new StringContent(postData);//設(shè)置Http的內(nèi)容標(biāo)頭httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");//設(shè)置Http的內(nèi)容標(biāo)頭的字符httpContent.Headers.ContentType.CharSet = "utf-8";HttpClientHandler httpHandler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };try{//using (HttpClient httpClient = new HttpClient(httpHandler))using (HttpClient httpClient = new HttpClient()){httpClient.Timeout = new TimeSpan(0, 0, 5);//異步PostHttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;//輸出Http響應(yīng)狀態(tài)碼httpStatusCode = response.StatusCode;//確保Http響應(yīng)成功if (response.IsSuccessStatusCode){//異步讀取jsonresult = response.Content.ReadAsStringAsync().Result;}else{LogHelper.Warn("調(diào)用后臺服務(wù)返回失敗:" + url + Environment.NewLine + SerializeObject(response));}}}catch (Exception ex){LogHelper.Error("調(diào)用后臺服務(wù)出現(xiàn)異常!", ex);}return result;}/// <summary>/// Post請求指定的URL地址/// </summary>/// <typeparam name="T">返回的json轉(zhuǎn)換成指定實體對象</typeparam>/// <param name="url">URL地址</param>/// <param name="postData">提交到Web的Json格式的數(shù)據(jù):如:{"ErrCode":"FileErr"}</param>/// <returns></returns>public static T PostWebAPI<T>(string url, string postData) where T : class, new(){T result = default(T);HttpContent httpContent = new StringContent(postData);httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");httpContent.Headers.ContentType.CharSet = "utf-8";HttpClientHandler httpHandler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };try{using (HttpClient httpClient = new HttpClient(httpHandler)){HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;if (response.IsSuccessStatusCode){Task<string> t = response.Content.ReadAsStringAsync();string s = t.Result;//Newtonsoft.Jsonstring jsonNamespace = DeserializeObject<T>(s).ToString();result = DeserializeObject<T>(s);}else{LogHelper.Warn("調(diào)用后臺服務(wù)返回失敗:" + url + Environment.NewLine + SerializeObject(response));}}}catch (Exception ex){LogHelper.Error("調(diào)用后臺服務(wù)出現(xiàn)異常!", ex);}return result;}/// <summary>/// Put請求指定的URL地址/// </summary>/// <param name="url">URL地址</param>/// <param name="putData">提交到Web的Json格式的數(shù)據(jù):如:{"ErrCode":"FileErr"}</param>/// <returns></returns>public static string PutWebAPI(string url, string putData){string result = "";string strOut = "";result = PutWebAPI(url, putData, out strOut);return result;}/// <summary>/// Put請求指定的URL地址/// </summary>/// <param name="url">URL地址</param>/// <param name="putData">提交到Web的Json格式的數(shù)據(jù):如:{"ErrCode":"FileErr"}</param>/// <param name="statusCode">Response返回的狀態(tài)</param>/// <returns></returns>public static string PutWebAPI(string url, string putData, out string statusCode){string result = statusCode = string.Empty;HttpContent httpContent = new StringContent(putData);httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");httpContent.Headers.ContentType.CharSet = "utf-8";try{using (HttpClient httpClient = new HttpClient()){HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;statusCode = response.StatusCode.ToString();if (response.IsSuccessStatusCode){result = response.Content.ReadAsStringAsync().Result;}else{LogHelper.Warn("調(diào)用后臺服務(wù)返回失敗:" + url + Environment.NewLine + SerializeObject(response));}}}catch (Exception ex){LogHelper.Error("調(diào)用后臺服務(wù)出現(xiàn)異常!", ex);}return result;}/// <summary>/// Put請求指定的URL地址/// </summary>/// <typeparam name="T">返回的json轉(zhuǎn)換成指定實體對象</typeparam>/// <param name="url">URL地址</param>/// <param name="putData">提交到Web的Json格式的數(shù)據(jù):如:{"ErrCode":"FileErr"}</param>/// <returns></returns>public static T PutWebAPI<T>(string url, string putData) where T : class, new(){T result = default(T);HttpContent httpContent = new StringContent(putData);httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");httpContent.Headers.ContentType.CharSet = "utf-8";try{using (HttpClient httpClient = new HttpClient()){HttpResponseMessage response = httpClient.PutAsync(url, httpContent).Result;if (response.IsSuccessStatusCode){Task<string> t = response.Content.ReadAsStringAsync();string s = t.Result;string jsonNamespace = DeserializeObject<T>(s).ToString();result = DeserializeObject<T>(s);}else{LogHelper.Warn("調(diào)用后臺服務(wù)返回失敗:" + url + Environment.NewLine + SerializeObject(response));}}}catch (Exception ex){LogHelper.Error("調(diào)用后臺服務(wù)出現(xiàn)異常!", ex);}return result;}/// <summary> /// 對象轉(zhuǎn)JSON /// </summary> /// <param name="obj">對象</param> /// <returns>JSON格式的字符串</returns> public static string SerializeObject(object obj){JavaScriptSerializer jss = new JavaScriptSerializer();try{return jss.Serialize(obj);}catch (Exception ex){LogHelper.Error("JSONHelper.SerializeObject 轉(zhuǎn)換對象失敗。", ex);throw new Exception("JSONHelper.SerializeObject(object obj): " + ex.Message);}}/// <summary>/// 將Json字符串轉(zhuǎn)換為對像 /// </summary>/// <typeparam name="T"></typeparam>/// <param name="json"></param>/// <returns></returns>public static T DeserializeObject<T>(string json){JavaScriptSerializer Serializer = new JavaScriptSerializer();T objs = default(T);try{objs = Serializer.Deserialize<T>(json);}catch (Exception ex){LogHelper.Error("JSONHelper.DeserializeObject 轉(zhuǎn)換對象失敗。", ex);throw new Exception("JSONHelper.DeserializeObject<T>(string json): " + ex.Message);}return objs;}#endregionprivate static HttpResponseMessage HttpPost(string url, HttpContent httpContent){HttpResponseMessage response = null;HttpClientHandler httpHandler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };try{//using (HttpClient httpClient = new HttpClient(httpHandler))using (HttpClient httpClient = new HttpClient()){httpClient.Timeout = new TimeSpan(0, 0, 5);//異步Postresponse = httpClient.PostAsync(url, httpContent).Result;}}catch (Exception ex){LogHelper.Error("調(diào)用后臺服務(wù)出現(xiàn)異常!", ex);}return response;}} }

?

下面再分享一個幫助類,有用到的做個參考吧

using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks;namespace WebCollect.CommonHelp {public static class CommonHelper{#region HttpClientprivate static HttpClient _httpClient;public static HttpClient httpClient{get{if (_httpClient == null){_httpClient = new HttpClient();_httpClient.Timeout = new TimeSpan(0, 1, 0);}return _httpClient;}set { _httpClient = value; }}#endregion#region get請求/// <summary>/// get請求返回的字符串/// </summary>/// <param name="url"></param>/// <returns></returns>public static string GetRequestStr(string url){try{var response = httpClient.GetAsync(new Uri(url)).Result;return response.Content.ReadAsStringAsync().Result;}catch (Exception){return null;}}/// <summary>/// get請求返回的二進(jìn)制/// </summary>/// <param name="url"></param>/// <returns></returns>public static byte[] GetRequestByteArr(string url){try{var response = httpClient.GetAsync(new Uri(url)).Result;return response.Content.ReadAsByteArrayAsync().Result;}catch (Exception){return null;}}#endregion#region post請求/// <summary>/// post請求返回的字符串/// </summary>/// <param name="url"></param>/// <returns></returns>public static string PostRequestStr(string url){try{string contentStr = "";StringContent sc = new StringContent(contentStr);sc.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");//todovar response = httpClient.PostAsync(new Uri(url), sc).Result;return response.Content.ReadAsStringAsync().Result;}catch (Exception){return null;}}#endregion} }

總結(jié)

以上是生活随笔為你收集整理的c#使用HttpClient调用WebApi的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。