博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c#使用HttpClient调用WebApi
阅读量:4303 次
发布时间:2019-05-27

本文共 19428 字,大约阅读时间需要 64 分钟。

可以利用HttpClient来进行Web Api的调用。由于WebA Api的调用本质上就是一次普通的发送请求与接收响应的过程,

所有HttpClient其实可以作为一般意义上发送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    {        ///         /// api调用方法/注意一下API地址        ///         /// 控制器名称--自己所需调用的控制器名称        /// 请求方式--get-post-delete-put        /// 方法名称--如需一个Id(方法名/ID)(方法名/?ID)根据你的API灵活运用        /// 方法参数--如提交操作传整个对象        /// 
json字符串--可以反序列化成你想要的
public static string GetApiMethod(string controllerName, string overb, string action, object obj = null) { Task
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

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

引用 Newtonsoft.Json  

复制代码

// Post请求        public string PostResponse(string url,string postData,out string statusCode)        {            string result = string.Empty;            //设置Http的正文            HttpContent httpContent = new StringContent(postData);            //设置Http的内容标头            httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");            //设置Http的内容标头的字符            httpContent.Headers.ContentType.CharSet = "utf-8";            using(HttpClient httpClient=new HttpClient())            {                //异步Post                HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;                //输出Http响应状态码                statusCode = response.StatusCode.ToString();                //确保Http响应成功                if (response.IsSuccessStatusCode)                {                    //异步读取json                    result = response.Content.ReadAsStringAsync().Result;                }            }            return result;        }        // 泛型:Post请求        public T PostResponse
(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
t = response.Content.ReadAsStringAsync(); string s = t.Result; //Newtonsoft.Json string json = JsonConvert.DeserializeObject(s).ToString(); result = JsonConvert.DeserializeObject
(json); } } return result; } // 泛型:Get请求 public T GetResponse
(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
t = response.Content.ReadAsStringAsync(); string s = t.Result; string json = JsonConvert.DeserializeObject(s).ToString(); result = JsonConvert.DeserializeObject
(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
(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
t = response.Content.ReadAsStringAsync(); string s = t.Result; string json = JsonConvert.DeserializeObject(s).ToString(); result = JsonConvert.DeserializeObject
(json); } } return result; }

复制代码

 

出处:

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

我自己把上面的修改下,可以不引用 Newtonsoft.Json  ,在POST模式的方法PostWebAPI增加了GZip的支持,请求超时设置,其他的功能可以自己去扩展,增加了简单调用的方式。

后续可以扩展异步方式、HttpWebRequest方式调用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        ///         /// Get请求指定的URL地址        ///         /// URL地址        /// 
public static string GetWebAPI(string url) { string result = ""; string strOut = ""; try { result = GetWebAPI(url, out strOut); } catch (Exception ex) { LogHelper.Error("调用后台服务出现异常!", ex); } return result; } /// /// Get请求指定的URL地址 /// /// URL地址 /// Response返回的状态 ///
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("调用后台服务返回失败:" + url + Environment.NewLine + SerializeObject(response)); } } } catch (Exception ex) { LogHelper.Error("调用后台服务出现异常!", ex); } return result; } /// /// Get请求指定的URL地址 /// ///
返回的json转换成指定实体对象
/// URL地址 ///
public static T GetWebAPI
(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
t = response.Content.ReadAsStringAsync(); string s = t.Result; string jsonNamespace = DeserializeObject
(s).ToString(); result = DeserializeObject
(s); } else { LogHelper.Warn("调用后台服务返回失败:" + url + Environment.NewLine + SerializeObject(response)); } } } catch (Exception ex) { LogHelper.Error("调用后台服务出现异常!", ex); } return result; } ///
/// Post请求指定的URL地址 /// ///
URL地址 ///
提交到Web的Json格式的数据:如:{"ErrCode":"FileErr"} ///
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("调用后台服务出现异常!", ex); } return result; } ///
/// Post请求指定的URL地址 /// ///
URL地址 ///
提交到Web的Json格式的数据:如:{"ErrCode":"FileErr"} ///
Response返回的状态 ///
public static string PostWebAPI(string url, string postData, out HttpStatusCode httpStatusCode) { string result = string.Empty; httpStatusCode = HttpStatusCode.BadRequest; //设置Http的正文 HttpContent httpContent = new StringContent(postData); //设置Http的内容标头 httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); //设置Http的内容标头的字符 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); //异步Post HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result; //输出Http响应状态码 httpStatusCode = response.StatusCode; //确保Http响应成功 if (response.IsSuccessStatusCode) { //异步读取json result = response.Content.ReadAsStringAsync().Result; } else { LogHelper.Warn("调用后台服务返回失败:" + url + Environment.NewLine + SerializeObject(response)); } } } catch (Exception ex) { LogHelper.Error("调用后台服务出现异常!", ex); } return result; } ///
/// Post请求指定的URL地址 /// ///
返回的json转换成指定实体对象
///
URL地址 ///
提交到Web的Json格式的数据:如:{"ErrCode":"FileErr"} ///
public static T PostWebAPI
(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
t = response.Content.ReadAsStringAsync(); string s = t.Result; //Newtonsoft.Json string jsonNamespace = DeserializeObject
(s).ToString(); result = DeserializeObject
(s); } else { LogHelper.Warn("调用后台服务返回失败:" + url + Environment.NewLine + SerializeObject(response)); } } } catch (Exception ex) { LogHelper.Error("调用后台服务出现异常!", ex); } return result; } ///
/// Put请求指定的URL地址 /// ///
URL地址 ///
提交到Web的Json格式的数据:如:{"ErrCode":"FileErr"} ///
public static string PutWebAPI(string url, string putData) { string result = ""; string strOut = ""; result = PutWebAPI(url, putData, out strOut); return result; } ///
/// Put请求指定的URL地址 /// ///
URL地址 ///
提交到Web的Json格式的数据:如:{"ErrCode":"FileErr"} ///
Response返回的状态 ///
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("调用后台服务返回失败:" + url + Environment.NewLine + SerializeObject(response)); } } } catch (Exception ex) { LogHelper.Error("调用后台服务出现异常!", ex); } return result; } ///
/// Put请求指定的URL地址 /// ///
返回的json转换成指定实体对象
///
URL地址 ///
提交到Web的Json格式的数据:如:{"ErrCode":"FileErr"} ///
public static T PutWebAPI
(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
t = response.Content.ReadAsStringAsync(); string s = t.Result; string jsonNamespace = DeserializeObject
(s).ToString(); result = DeserializeObject
(s); } else { LogHelper.Warn("调用后台服务返回失败:" + url + Environment.NewLine + SerializeObject(response)); } } } catch (Exception ex) { LogHelper.Error("调用后台服务出现异常!", ex); } return result; } ///
/// 对象转JSON /// ///
对象 ///
JSON格式的字符串
public static string SerializeObject(object obj) { JavaScriptSerializer jss = new JavaScriptSerializer(); try { return jss.Serialize(obj); } catch (Exception ex) { LogHelper.Error("JSONHelper.SerializeObject 转换对象失败。", ex); throw new Exception("JSONHelper.SerializeObject(object obj): " + ex.Message); } } ///
/// 将Json字符串转换为对像 /// ///
///
///
public static T DeserializeObject
(string json) { JavaScriptSerializer Serializer = new JavaScriptSerializer(); T objs = default(T); try { objs = Serializer.Deserialize
(json); } catch (Exception ex) { LogHelper.Error("JSONHelper.DeserializeObject 转换对象失败。", ex); throw new Exception("JSONHelper.DeserializeObject
(string json): " + ex.Message); } return objs; } #endregion private 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); //异步Post response = httpClient.PostAsync(url, httpContent).Result; } } catch (Exception ex) { LogHelper.Error("调用后台服务出现异常!", 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 HttpClient        private 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请求        ///         /// get请求返回的字符串        ///         ///         /// 
public static string GetRequestStr(string url) { try { var response = httpClient.GetAsync(new Uri(url)).Result; return response.Content.ReadAsStringAsync().Result; } catch (Exception) { return null; } } /// /// get请求返回的二进制 /// /// ///
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请求 /// /// post请求返回的字符串 /// /// ///
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");//todo var response = httpClient.PostAsync(new Uri(url), sc).Result; return response.Content.ReadAsStringAsync().Result; } catch (Exception) { return null; } } #endregion }}

复制代码

转载地址:http://inlws.baihongyu.com/

你可能感兴趣的文章
原理性地理解 Java 泛型中的 extends、super 及 Kotlin 的协变、逆变
查看>>
FFmpeg 是如何实现多态的?
查看>>
FFmpeg 源码分析 - avcodec_send_packet 和 avcodec_receive_frame
查看>>
FFmpeg 新旧版本编码 API 的区别
查看>>
RecyclerView 源码深入解析——绘制流程、缓存机制、动画等
查看>>
Android 面试题整理总结(一)Java 基础
查看>>
Android 面试题整理总结(二)Java 集合
查看>>
学习笔记_vnpy实战培训day02
查看>>
学习笔记_vnpy实战培训day03
查看>>
VNPY- VnTrader基本使用
查看>>
VNPY - CTA策略模块策略开发
查看>>
VNPY - 事件引擎
查看>>
MongoDB基本语法和操作入门
查看>>
学习笔记_vnpy实战培训day04_作业
查看>>
OCO订单(委托)
查看>>
学习笔记_vnpy实战培训day05
查看>>
学习笔记_vnpy实战培训day06
查看>>
Python super钻石继承
查看>>
回测引擎代码分析流程图
查看>>
Excel 如何制作时间轴
查看>>