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 ...
随机推荐
- Sublime Text3插件安装(经典)
今天我去听数学建模的培训,感觉很有意思,可是我没有报名(QAQ),没有参加培训的报名,不过幸好没有开始选拔比赛 所以我决定学习数学建模方面的知识,要好好学习了! 希望我未来的学弟学妹们!(不要像我这样 ...
- Description Resource Path Location Type Cannot change version of project facet Dynamic Web Module to 2.3.
报错信息:Description Resource Path Location Type Cannot change version of project facet Dynamic Web Modu ...
- java 基本类型包装类,system类,Math类,Assrays类,大数据运算
实现字符串与基本数据之间转换 将字符串转成基本数据类型方法 例如:将字符串转成成int类型 String str ="123"; int a =Integer.parseInt(s ...
- ABP入门系列目录——学习Abp框架之实操演练
ABP是"ASP.NET Boilerplate Project (ASP.NET样板项目)"的简称. ASP.NET Boilerplate是一个用最佳实践和流行技术开发现代WE ...
- android使用.9图作为背景,内容不能居中的问题解决方案
在xml中使用.9图作为背景,内容不能居中,试了好多方法最后,加一个属性就ok了. android:padding:0dip; 解析:.9图作为背景时,不可拉伸的部分就相当于该空间的padding距离 ...
- 设计模式之Singleton模式和Strategy模式是什么
Singleton模式 单例模式,也交单子模式,有时候系统只需要拥有一个全局对象. 这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建.这个类提供了一种访问其唯一的对象的方 ...
- Windows 安装 Scoop
Scoop介绍 scoop是Windows下的包管理工具 安装环境要求 1,操作环境:win10 2,确保你的 PowerShell 版本 >= 3. win7或许低于3,得升级.如何确认Pow ...
- libaio.so.1()(64bit) is needed by MySQL-server 问题解决办法
[root@localhost upload]# rpm -ivh MySQL-server-5.5.25a-1.rhel5.x86_64.rpmerror: Failed dependencies: ...
- 好程序员web前端分享CSS基础篇
学习目标 1.CSS简介 2.CSS语法 3.样式的创建 4.两种引入外部样式表的区别 5.样式表的优先级和作用域 6.CSS选择器 7.选择器的权重 8.浮动属性的简单应用 9.HTML.CSS注释 ...
- Ubuntu16 Nginx的安装与基本配置
关于Nginx 它是一个轻量级.高性能.稳定性高.并发性好的HTTP和反向代理服务器,当我们搭建自己的应用时,通常用它作为反向代理服务器,图片服务器和负载均衡. 1.Ubuntu 16安装 Nginx ...