C#封装HttpClient工具类库(.NET4.5以上)
1、Json字符串实体转换扩展方法,依赖Json.Net包
/// <summary>
/// Json扩展方法
/// </summary>
public static class JsonExtends
{
public static T ToEntity<T>(this string val)
{
return JsonConvert.DeserializeObject<T>(val);
} //public static List<T> ToEntityList<T>(this string val)
//{
// return JsonConvert.DeserializeObject<List<T>>(val);
//}
public static string ToJson<T>(this T entity, Formatting formatting = Formatting.None)
{
return JsonConvert.SerializeObject(entity, formatting);
}
}
2、HttpHelper封装类
public class HttpHelper
{
/// <summary>
/// 发起POST同步请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="headers">填充消息头</param>
/// <returns></returns>
public static string HttpPost(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
{
postData = postData ?? "";
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
} /// <summary>
/// 发起POST异步请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="headers">填充消息头</param>
/// <returns></returns>
public static async Task<string> HttpPostAsync(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
{
postData = postData ?? "";
using (HttpClient client = new HttpClient())
{
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = await client.PostAsync(url, httpContent);
return await response.Content.ReadAsStringAsync();
}
}
} /// <summary>
/// 发起GET同步请求
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <returns></returns>
public static string HttpGet(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType != null)
client.DefaultRequestHeaders.Add("ContentType", contentType);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
HttpResponseMessage response = client.GetAsync(url).Result;
return response.Content.ReadAsStringAsync().Result;
}
} /// <summary>
/// 发起GET异步请求
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <returns></returns>
public static async Task<string> HttpGetAsync(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
{
using (HttpClient client = new HttpClient())
{
if (contentType != null)
client.DefaultRequestHeaders.Add("ContentType", contentType);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
HttpResponseMessage response = await client.GetAsync(url);
return await response.Content.ReadAsStringAsync();
}
} /// <summary>
/// 发起POST同步请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="headers">填充消息头</param>
/// <returns></returns>
public static T HttpPost<T>(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
{
return HttpPost(url, postData, contentType, timeOut, headers).ToEntity<T>();
} /// <summary>
/// 发起POST异步请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="headers">填充消息头</param>
/// <returns></returns>
public static async Task<T> HttpPostAsync<T>(string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
{
var res = await HttpPostAsync(url, postData, contentType, timeOut, headers);
return res.ToEntity<T>();
} /// <summary>
/// 发起GET同步请求
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <returns></returns>
public static T HttpGet<T>(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
{
return HttpGet(url, contentType, headers).ToEntity<T>();
} /// <summary>
/// 发起GET异步请求
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <returns></returns>
public static async Task<T> HttpGetAsync<T>(string url, string contentType = "application/json", Dictionary<string, string> headers = null)
{
var res = await HttpGetAsync(url, contentType, headers);
return res.ToEntity<T>();
}
}
3、辅助扩展方法
public static class HttpExtension
{
/// <summary>
/// 发起GET同步请求
/// </summary>
/// <param name="client"></param>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <returns></returns>
public static string HttpGet(this HttpClient client, string url, string contentType = "application/json",
Dictionary<string, string> headers = null)
{
if (contentType != null)
client.DefaultRequestHeaders.Add("ContentType", contentType);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
HttpResponseMessage response = client.GetAsync(url).Result;
return response.Content.ReadAsStringAsync().Result;
} /// <summary>
/// 发起GET异步请求
/// </summary>
/// <param name="client"></param>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <returns></returns>
public static async Task<string> HttpGetAsync(this HttpClient client, string url, string contentType = "application/json", Dictionary<string, string> headers = null)
{
if (contentType != null)
client.DefaultRequestHeaders.Add("ContentType", contentType);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
HttpResponseMessage response = await client.GetAsync(url);
return await response.Content.ReadAsStringAsync();
} /// <summary>
/// 发起POST同步请求
/// </summary>
/// <param name="client"></param>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="timeOut"></param>
/// <param name="headers">填充消息头</param>
/// <returns></returns>
public static string HttpPost(this HttpClient client, string url, string postData = null,
string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
{
postData = postData ?? "";
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
return response.Content.ReadAsStringAsync().Result;
}
} /// <summary>
/// 发起POST异步请求
/// </summary>
/// <param name="client"></param>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="headers">填充消息头</param>
/// <returns></returns>
public static async Task<string> HttpPostAsync(this HttpClient client, string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
{
postData = postData ?? "";
client.Timeout = new TimeSpan(0, 0, timeOut);
if (headers != null)
{
foreach (var header in headers)
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
{
if (contentType != null)
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType); HttpResponseMessage response = await client.PostAsync(url, httpContent);
return await response.Content.ReadAsStringAsync();
}
} /// <summary>
/// 发起POST同步请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="headers">填充消息头</param>
/// <returns></returns>
public static T HttpPost<T>(this HttpClient client, string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
{
return client.HttpPost(url, postData, contentType, timeOut, headers).ToEntity<T>();
} /// <summary>
/// 发起POST异步请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="headers">填充消息头</param>
/// <returns></returns>
public static async Task<T> HttpPostAsync<T>(this HttpClient client, string url, string postData = null, string contentType = "application/json", int timeOut = 30, Dictionary<string, string> headers = null)
{
var res = await client.HttpPostAsync(url, postData, contentType, timeOut, headers);
return res.ToEntity<T>();
} /// <summary>
/// 发起GET同步请求
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <returns></returns>
public static T HttpGet<T>(this HttpClient client, string url, string contentType = "application/json", Dictionary<string, string> headers = null)
{
return client.HttpGet(url, contentType, headers).ToEntity<T>();
} /// <summary>
/// 发起GET异步请求
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <returns></returns>
public static async Task<T> HttpGetAsync<T>(this HttpClient client, string url, string contentType = "application/json", Dictionary<string, string> headers = null)
{
var res = await client.HttpGetAsync(url, contentType, headers);
return res.ToEntity<T>();
}
}
C#封装HttpClient工具类库(.NET4.5以上)的更多相关文章
- 转:轻松把玩HttpClient之封装HttpClient工具类(一)(现有网上分享中的最强大的工具类)
搜了一下网络上别人封装的HttpClient,大部分特别简单,有一些看起来比较高级,但是用起来都不怎么好用.调用关系不清楚,结构有点混乱.所以也就萌生了自己封装HttpClient工具类的想法.要做就 ...
- C#封装MongoDB工具类库
什么是MongoDB MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统. 在高负载的情况下,添加更多的节点,可以保证服务器性能. MongoDB 旨在为WEB应用提供可扩 ...
- 轻松把玩HttpClient之封装HttpClient工具类(五),携带Cookie的请求
近期更新了一下HttpClientUtil工具类代码,主要是加入了一个參数HttpContext,这个是用来干嘛的呢?事实上是用来保存和传递Cookie所须要的. 由于我们有非常多时候都须要登录.然后 ...
- Java开发小技巧(五):HttpClient工具类
前言 大多数Java应用程序都会通过HTTP协议来调用接口访问各种网络资源,JDK也提供了相应的HTTP工具包,但是使用起来不够方便灵活,所以我们可以利用Apache的HttpClient来封装一个具 ...
- 编写更少量的代码:使用apache commons工具类库
Commons-configuration Commons-FileUpload Commons DbUtils Commons BeanUtils Commons CLI Commo ...
- Flutter 常用工具类库common_utils
地址:https://pub.flutter-io.cn/packages/common_utils#-readme-tab- Dart常用工具类库 common_utils 1.TimelineUt ...
- Java程序员都应该去使用一下这款强大的国产工具类库
这不是标题党,今天给大家推荐一个很棒的国产工具类库:Hutool.可能有很多朋友已经知道这个类库了,甚至在已经在使用了,如果你还没有使用过,那不妨去尝试一下,我们项目组目前也在用这个.这篇文章来简单介 ...
- Apache—dbutils开源JDBC工具类库简介
Apache—dbutils开源JDBC工具类库简介 一.前言 commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用 ...
- 【Java基础】Java开发过程中的常用工具类库
目录 Java开发过程中的常用工具类库 1. Apache Commons类库 2. Guava类库 3. Spring中的常用工具类 4. 其他工具 参考 Java开发过程中的常用工具类库 1. A ...
- Java程序员常用工具类库
有人说当你开始学习Java的时候,你就走上了一条不归路,在Java世界里,包罗万象,从J2SE,J2ME,J2EE三大平台,到J2EE中的13中核心技术,再到Java世界中万紫千红的Framework ...
随机推荐
- Vue cli之安装
1.安装node.js Node.js是一个新的后端(后台)语言,它的语法和JavaScript类似,所以可以说它是属于前端的后端语言,后端语言和前端语言的区别: 运行环境:后端语言一般运行在服务器端 ...
- HTML——select下拉选择标签
select的基本语法: <select> <option></option> </select> 例子: <p>籍贯: <selec ...
- UILabel的DrawDrect方法
一.问题 如果继承UILabel实现自己的一个Label,并且在子类的DrawRect方法中留空,什么都不写,会发生什么? 代码如下: VC @interface ViewController () ...
- QuartusII调用 PLL_IP核方法(Mega Wizard)
[基本信息] 要求:调用PLL-IP核,50Mhz晶振输入,输出四路时钟不同信号:100Mhz,25Mhz,50Mhz(90°相位),50Mhz(20%占空比). 芯片型号:cyclone Ⅳ EP4 ...
- windows隐藏文件如何查看
1.组织 2.查看 3.显示隐藏文件
- Linux设备驱动--轮询操作
注:本文是<Linux设备驱动开发详解:基于最新的Linux 4.0内核 by 宋宝华 >一书学习的笔记,大部分内容为书籍中的内容. 书籍可直接在微信读书中查看:Linux设备驱动开发详解 ...
- Centos7无法ping通内网、外网
主要检查网络的配置是否正确,我测试时使用的是VMware虚拟机,需要保证centos中的网络配置和VMware中的一致. (1)VMware的配置 网络适配器选择NAT模式 查看NAT设置,这里需要记 ...
- Vue学习:22.Vue组件库-Vant
Vue组件库是一系列预先构建好的.可复用的UI组件集合,它们设计用于加速Vue.js应用程序的开发过程.这些组件通常遵循一定的设计规范,提供统一的外观和交互体验,让开发者能够快速搭建用户界面. 组件库 ...
- 浅拷贝、深拷贝与序列化【初级Java必需理解的概念】
浅拷贝 首先创建两个类,方便理解浅拷贝 @Data class Student implements Cloneable{ //年龄和名字是基本属性 private int age; private ...
- Unity中使用ProtocolBuffer
Unity中使用ProtocolBuffer unityProtocolBufferUnity ProtocolBuggerC# ProtocolBuffer Unity中使用ProtocolBuff ...