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 ...
随机推荐
- FFmpeg开发笔记(二十四)Linux环境给FFmpeg集成AV1的编解码器
AV1是一种新兴的免费视频编码标准,它由开放媒体联盟(Alliance for Open Media,简称AOM)于2018年制定,融合了Google VP10.Mozilla Daala以及Cis ...
- Android 12(S) Binder(一)
今天开始了解一下binder,就先从ServiceManager开始学习. 网上的相关博文普遍是Android 11之前的,阅读时对比Android 11或12的代码发现有很多内容找不到了,比如 fr ...
- Http 代理工具 实战 支持网页与QQ代理
前言: 有些公司不让员工上Q或封掉某些网站,这时候,干着急没办法,只能鄱墙.如果上网搜代理IP,很少能用,用HTTP-Tunnel Client代理软件,免费的也是经常性的掉线.正好手头上有N台服务器 ...
- Yarp 让系统内调度更灵活 http、https、websocket 反向代理
简介 Yarp 是微软团队开发的一个反向代理组件, 除了常规的 http 和 https 转换通讯,它最大的特点是可定制化,很容易根据特定场景开发出需要的定制代理通道. 详细介绍:https://de ...
- 通过 InnoSetup 美化安装界面
InnoSetup 的美化相应的帖子也比较多,但是代码不是很全...所以我专门出了这篇文章来记录下这个美化过程.废话不多说,先上个成果: 前端er们可以直接下载 vue-nw-seed 这个分支,一键 ...
- windows安装mysql8(5分钟)
1.下载 MySQL https://dev.mysql.com/downloads/mysql/ 下载完成后,解压缩到你的目录里. 2.配置 MySQL 的配置文件 创建一个文件,名称为:my.in ...
- Mysql 5.7 及以上版本修改密码
登录数据后.选择 mysql 数据库 use mysql; 修改密码 update user set authentication_string=PASSWORD("mynewpasswor ...
- 使用final shell 连接使用 ubuntu server linux
书接上回,VM 安装ubuntu server:https://www.cnblogs.com/runliuv/p/16880599.html 1.从 https://www.hostbuf.com/ ...
- maven常用命令大全(附详细解释)
1.常用打包命令 mvn clean package -Dmaven.test.skip=true -- 跳过单测打包mvn clean install -Dmaven.test.skip=true ...
- 直播预告|把握转型浪潮下的机会,甄知科技教你保姆级IT服务管理
近年来,5G.云计算.大数据.物联网.区块链.人工智能等新兴技术不断在企业中协同发展应用,推动着企业的数字化程度逐步加深.自新冠疫情发生以来,企业的远程服务.服务自助等服务需求激增,企业数字化转型需求 ...