HttpClient封装方法
//post请求
public static string PostRequest(string url, HttpContent data)
{
var handler = new HttpClientHandler() { UseCookies = false };
HttpClient client = new HttpClient(handler);
var message = new HttpRequestMessage(HttpMethod.Post, url);
message.Content = data;
//message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", GetRemoteToken());
var response = client.SendAsync(message).Result;
response.EnsureSuccessStatusCode();
var result = response.Content.ReadAsStringAsync().Result;
return result;
} //发送文件
public static void SendFile(string url,string path = @"C:\<filepath>\test.txt")
{
using (var client = new HttpClient())
using (var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri("http://localhost"); var fileContent1 = new ByteArrayContent(File.ReadAllBytes(path));
fileContent1.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(path)
};
content.Add(fileContent1); var result = client.PostAsync(url, content).Result;
}
}
/// <summary>
/// Http请求帮助类
/// </summary>
public class HttpHelper
{
/// <summary>
/// 同步GET请求
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
/// <returns></returns>
public static string HttpGet(string url, Dictionary<string, string> headers = null, int timeout = 0)
{
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (KeyValuePair<string, string> header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = new TimeSpan(0, 0, timeout);
}
Byte[] resultBytes = client.GetByteArrayAsync(url).Result;
return Encoding.UTF8.GetString(resultBytes);
}
}
/// <summary>
/// 异步GET请求
/// </summary>
/// <param name="url"></param>
/// <param name="headers"></param>
/// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
/// <returns></returns>
public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null, int timeout = 0)
{
using (HttpClient client = new HttpClient())
{
if (headers != null)
{
foreach (KeyValuePair<string, string> header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = new TimeSpan(0, 0, timeout);
}
Byte[] resultBytes = await client.GetByteArrayAsync(url);
return Encoding.Default.GetString(resultBytes);
}
} /// <summary>
/// 同步POST请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
/// <param name="encoding">默认UTF8</param>
/// <returns></returns>
public static string HttpPost(string url, string postData, Dictionary<string, string> headers = null, string contentType = null, int timeout = 0, Encoding encoding = null)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36");
if (headers != null)
{
foreach (KeyValuePair<string, string> header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = new TimeSpan(0, 0, timeout);
}
using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
{
if (contentType != null)
{
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
}
using (HttpResponseMessage responseMessage = client.PostAsync(url, content).Result)
{
Byte[] resultBytes = responseMessage.Content.ReadAsByteArrayAsync().Result;
return Encoding.UTF8.GetString(resultBytes);
}
}
}
} /// <summary>
/// 异步POST请求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="headers"></param>
/// <param name="contentType"></param>
/// <param name="timeout">请求响应超时时间,单位/s(默认100秒)</param>
/// <param name="encoding">默认UTF8</param>
/// <returns></returns>
public static async Task<string> HttpPostAsync(string url, string postData, Dictionary<string, string> headers = null, string contentType = null, int timeout = 0, Encoding encoding = null)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36");
if (headers != null)
{
foreach (KeyValuePair<string, string> header in headers)
{
client.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
if (timeout > 0)
{
client.Timeout = new TimeSpan(0, 0, timeout);
}
using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
{
if (contentType != null)
{
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
}
using (HttpResponseMessage responseMessage = await client.PostAsync(url, content))
{
Byte[] resultBytes = await responseMessage.Content.ReadAsByteArrayAsync();
return Encoding.UTF8.GetString(resultBytes);
}
}
}
}
}
//httpcontent类型
//json
HttpContent content1 = new StringContent("{a:1,b:2}", Encoding.UTF8, "application/json");
//from
HttpContent content2 = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"email", "1"},
{"pwd","11"}
});
HttpClient封装方法的更多相关文章
- .Net基础——程序集与CIL HttpClient封装方法 .Net Core 编码规范 C#中invoke和beginInvoke的使用 WebServeice 动态代理类
.Net基础——程序集与CIL 1. 程序集和CIL: 程序集是由.NET语言的编译器接受源代码文件产生的输出文件,通常分为 exe和dll两类,其中exe包含Main入口方法可以双击执行,dll ...
- httpclient获取响应实体和信息的封装方法(解耦更新)
转自:https://blog.csdn.net/fhaohaizi/article/details/77850302 2018年07月19日更新,主要是解耦之后方法很多地方发生了变化,httpcli ...
- js面向对象的封装方法,【案例】
封装方法: /** * @矩形canvas库 * @authors Shimily (275766400@qq.com) * @date 2016-12-28 10:30:51 * @version ...
- Javascript 封装方法
基本封装方法 请看下面的例子: var Person = function(name,age){ this.name = name; this.age = age || "未填写" ...
- [论文笔记] 一种Java遗留系统服务化切分和封装方法 (计算机学报, 2009)
李翔,怀进鹏,曾晋,高鹏. 一种Java遗留系统服务化切分和封装方法. 计算机学报, 32(9), 2009, p1084-1815 (gs:5) 1. 本文研究从Java遗留系统中切分并封装出Web ...
- httpclient请求方法
/** * httpclient请求方法 * @param url 请求地址 * @param paramMap 请求参数 * @param ent 编码格式 gbk.utf-8 * @return ...
- 分享几个Javascript 封装方法
基本封装方法 请看下面的例子: var Person = function(name,age){ this.name = name; this.age = age || "未填写" ...
- iOS常用的封装方法
做开发也有一段时间了,看了好多大神的代码,总体感觉他们写的代码简洁,好看,然而在对比下我写的代码,混乱,无序,简直不堪入目啊! 总体来说大神们的代码封装的都比较好,对一个项目要重复用到的代码他们都会封 ...
- JavaScrpt常用的封装方法
1.闭包封装.在这个封装方法中,所有的实例成员都共享属性和方法, 使得所有得方法和属性都私有且对象间共享 (function ($) { var Person = function(name) { r ...
随机推荐
- Python数据结构应用5——排序(Sorting)
在具体算法之前,首先来看一下排序算法衡量的标准: 比较:比较两个数的大小的次数所花费的时间. 交换:当发现某个数不在适当的位置时,将其交换到合适位置花费的时间. 冒泡排序(Bubble Sort) 这 ...
- 有趣的8个IT冷知识
阅读本文大概需要 2.8 分钟. 想要成为一名成功的程序员,我们除了了解不同编程语言的设计思路,也应当了解编程的发展历史,从而判断未来的编程技术将走向何方.接下就为大家普及下计算机发展历程中的8个冷门 ...
- Python-炫酷二维码
一.环境 首先是安装python环境,如果没有安装python环境看此处 二.myqr myqr 其实是一个 python 的脚本,可以生产二维码图片,作者也对python脚本进行了打包,在 ...
- .net core 注入中的三种模式:Singleton、Scoped 和 Transient
从上篇内容不如题的文章<.net core 并发下的线程安全问题>扩展认识.net core注入中的三种模式:Singleton.Scoped 和 Transient 我们都知道在 Sta ...
- synchronized关键字简介 多线程中篇(十一)
前面说过,Java对象都有与之关联的一个内部锁和监视器 内部锁是一种排它锁,能够保障原子性.可见性.有序性 从Java语言层面上说,内部锁使用synchronized关键字实现 synchronize ...
- linux、shell一些操作指令
1.cd $(dirname $0) shell脚本里面添加这个命令就可以进入此sh目录下,不用写绝对路径 2.strMac=`ifconfig eth0 | grep "HWaddr& ...
- QT文件操作
/* 写文件 */ QFile file(filePath); bool bo = file.open(QIODevice::WriteOnly | QIODevice::Append); //qDe ...
- 编程心法 之 敏捷开发(新架构)Agile Team Organization Squads, Chapters, Tribes and Guilds
Agile Team 参考 一般情况下,一个小组有以下功能分布: Squads 每个主要的功能的开发属于一个Squad,比如说QQ这个应用,可以分为QQ空间小组.QQ会员小组等等, 每一个Squad有 ...
- Postman 安装
前言 安装前的准备: 1.Chrome 浏览器的扩展插件来进行的安装,并非单独应用程序. 2.电脑上已经安装了 Chrome 浏览器 3.本文章适用操作系统 window7 一,非官方安装 个人不建 ...
- pytest框架之命令行参数1
前言 pytest是一款强大的python自动化测试工具,可以胜任各种类型或者级别的软件测试工作.pytest提供了丰富的功能,包括assert重写,第三方插件,以及其他测试工具无法比拟的fixtur ...