//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封装方法的更多相关文章

  1. .Net基础——程序集与CIL HttpClient封装方法 .Net Core 编码规范 C#中invoke和beginInvoke的使用 WebServeice 动态代理类

    .Net基础——程序集与CIL   1. 程序集和CIL: 程序集是由.NET语言的编译器接受源代码文件产生的输出文件,通常分为 exe和dll两类,其中exe包含Main入口方法可以双击执行,dll ...

  2. httpclient获取响应实体和信息的封装方法(解耦更新)

    转自:https://blog.csdn.net/fhaohaizi/article/details/77850302 2018年07月19日更新,主要是解耦之后方法很多地方发生了变化,httpcli ...

  3. js面向对象的封装方法,【案例】

    封装方法: /** * @矩形canvas库 * @authors Shimily (275766400@qq.com) * @date 2016-12-28 10:30:51 * @version ...

  4. Javascript 封装方法

    基本封装方法 请看下面的例子: var Person = function(name,age){ this.name = name; this.age = age || "未填写" ...

  5. [论文笔记] 一种Java遗留系统服务化切分和封装方法 (计算机学报, 2009)

    李翔,怀进鹏,曾晋,高鹏. 一种Java遗留系统服务化切分和封装方法. 计算机学报, 32(9), 2009, p1084-1815 (gs:5) 1. 本文研究从Java遗留系统中切分并封装出Web ...

  6. httpclient请求方法

    /** * httpclient请求方法 * @param url 请求地址 * @param paramMap 请求参数 * @param ent 编码格式 gbk.utf-8 * @return ...

  7. 分享几个Javascript 封装方法

    基本封装方法 请看下面的例子: var Person = function(name,age){ this.name = name; this.age = age || "未填写" ...

  8. iOS常用的封装方法

    做开发也有一段时间了,看了好多大神的代码,总体感觉他们写的代码简洁,好看,然而在对比下我写的代码,混乱,无序,简直不堪入目啊! 总体来说大神们的代码封装的都比较好,对一个项目要重复用到的代码他们都会封 ...

  9. JavaScrpt常用的封装方法

    1.闭包封装.在这个封装方法中,所有的实例成员都共享属性和方法, 使得所有得方法和属性都私有且对象间共享 (function ($) { var Person = function(name) { r ...

随机推荐

  1. 从字节码和JVM的角度解析Java核心类String的不可变特性

    1. 前言 最近看到几个有趣的关于Java核心类String的问题. String类是如何实现其不可变的特性的,设计成不可变的好处在哪里. 为什么不推荐使用+号的方式去形成新的字符串,推荐使用Stri ...

  2. 使用Onenote & Evernote & VSC+Markdown构建个人笔记系统

    Onenote & Evernote & VSC+Markdown构建个人笔记系统 umeowbing(转载请注明出处) 1 Why 笔记本太多,全部带着太重,查找起来也很麻烦-- 笔 ...

  3. python——报错ImportError:DLL load failed with error code -1073741795的解决方式

    python中导入一个包,import cv2总是报错'ImportError:DLL load failed with error code -1073741795',报错形式: 网上找了好久的解决 ...

  4. SpringBoot(三)_controller的使用

    针对controller 中 如何使用注解进行解析 @RestController 返回数据类型为 Json 字符串,特别适合我们给其他系统提供接口时使用. @RequestMapping (1) 不 ...

  5. 8000个JQuery特效(插件)

    各式各样的JQuery场景实现,可供项目使用,请注意插件版本和浏览器适配 下面是下载地址

  6. Java相关面试题总结

    本文分为十九个模块,分别是: Java 基础.容器.多线程.反射.对象拷贝.Java Web .异常.网络.设计模式.Spring/Spring MVC.Spring Boot/Spring Clou ...

  7. 如何使用FluentMigrator进行数据库迁移

    标题:如何使用FluentMigrator进行数据库迁移 地址:https://www.cnblogs.com/lwqlun/p/10649949.html 作者: Lamond Lu FluentM ...

  8. 别开心太早,Python 官方文档的翻译差远了

    近几天,很多公众号发布了 Python 官方文档的消息.然而,一个特别奇怪的现象就发生了,让人啼笑皆非. Python 文档的中文翻译工作一直是“默默无闻”,几个月前,我还吐槽过这件事<再聊聊P ...

  9. Centos7 nginx 虚拟主机、反向代理服务器及负载均衡,多台主机分离php-fpm实验,之强化篇,部署zabbix为例

    一.简介 1.由于zabbix是php得,所有lnmp环境这里测试用的上一个实验环境,请查看https://www.cnblogs.com/zhangxingeng/p/10330735.html : ...

  10. 关于RecyclerView嵌套导致item复用异常,界面异常的问题

    常规需求: 外层RecyclerView嵌套内层RecyclerView , 在上下滑动的时候会出现item数据以及view的显示异常. 解决办法: 1.重写  getItemViewType  方法 ...