多线程之HttpClient
在程序用调用 Http 接口、请求 http 资源、编写 http 爬虫等的时候都需要在程序集中进行 Http 请求。
很多人习惯的 WebClient、HttpWebRequest 在 TPL 下很多用起来不方便的地方,TPL 下推荐使用 HttpClient(using System.Net.Http;),.net core 下已经不支持 WebClient 等
HttpClient 发 出 Get 请 求 获 取 文 本 响 应 : string html = await hc.GetStringAsync("http://www.rupeng.com");
HttpClient 发出Post请求使用
//第一个参数是请求的地址,第二个参数就是用来设置请求内容的
Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
HttpContent是一个抽象类:主要的子类有:
- FormUrlEncodedContent(表单格式请求)、
- StringContent(字符串请求)、
- MultipartFormDataContent(Multipart 表单请求,一般带上传文件信息)、
- StreamContent(流内容)。
发送一个Get请求
private async void button1_Click(object sender, EventArgs e)
{
//发送异步的Get请求
HttpClient hc = new HttpClient();
//await hc.GetByteArrayAsync()
//await hc.GetStreamAsync()
string html=await hc.GetStringAsync("http://127.0.0.1:8081/Home/Login");
textBox1.Text = html;
}
发送一个POST表单格式请求:
private async void button2_Click(object sender, EventArgs e)
{
HttpClient hc = new HttpClient();
//List<KeyValuePair<string, string>> nameValues = new List<KeyValuePair<string, string>>();
//nameValues.Add(new KeyValuePair<string, string>("userName", "admin123"));
//nameValues.Add(new KeyValuePair<string, string>("password", "123123123"));
//Dictionary也是实现了IEnumerable接口的,所以也可以这样传值
Dictionary<string, string> nameValues = new Dictionary<string, string>();
nameValues["userName"] = "admin123";
nameValues["password"] = "";
FormUrlEncodedContent content = new FormUrlEncodedContent(nameValues);
HttpResponseMessage msg= await hc.PostAsync("http://127.0.0.1:8081/Home/Login", content);
//msg.Content;返回的Http报问题
//msg.Headers;获得响应头
//msg.StatusCode;获得响应的状态码 }
发送一个POST字符串请求:
private async void button3_Click(object sender, EventArgs e)
{
string json = "{userName:'admin',password:'123'}";
HttpClient client = new HttpClient();
StringContent content = new StringContent(json);
//contentype 设置协议类型,必不可少
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var respMsg = await client.PostAsync("http://127.0.0.1:6666/Home/Login2/", content);
string msgBody = await respMsg.Content.ReadAsStringAsync();
}
发送一个POST,Multipart 表单上传请求:
private async void button4_Click(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
MultipartFormDataContent content = new MultipartFormDataContent();
content.Headers.Add("UserName", "admin");
content.Headers.Add("Password", "");
//先读取文件
using (Stream stream = File.OpenRead(@"D:\temp\xx.png"))
{
// 放入流中 上传接口协议名file 文件名
content.Add(new StreamContent(stream), "file", "logo.png");
var respMsg = await client.PostAsync("http://127.0.0.1:6666/Home/Upload/", content);
string msgBody = await respMsg.Content.ReadAsStringAsync();
MessageBox.Show(respMsg.StatusCode.ToString());
MessageBox.Show(msgBody);
}
}
多线程之HttpClient的更多相关文章
- Android-——多线程之Handler(转)
Android--多线程之Handler 原文地址:http://www.cnblogs.com/shirley-1019/p/3557800.html 前言 Android的消息传递机制是另外一种形 ...
- iOS多线程之8.NSOPeration的其他用法
本文主要对NSOPeration的一些重点属性和方法做出介绍,以便大家可以更好的使用NSOPeration. 1.添加依赖 - (void)addDependency:(NSOperation * ...
- python 线程之 threading(四)
python 线程之 threading(三) http://www.cnblogs.com/someoneHan/p/6213100.html中对Event做了简单的介绍. 但是如果线程打算一遍一遍 ...
- python 线程之 threading(三)
python 线程之 threading(一)http://www.cnblogs.com/someoneHan/p/6204640.html python 线程之 threading(二)http: ...
- python 线程之_thread
python 线程之_thread _thread module: 基本用法: def child(tid): print("hello from child",tid) _thr ...
- [深入浅出WP8.1(Runtime)]网络编程之HttpClient类
12.2 网络编程之HttpClient类 除了可以使用HttpWebRequest类来实现HTTP网络请求之外,我们还可以使用HttpClient类来实现.对于基本的请求操作,HttpClient类 ...
- Java多线程之ConcurrentSkipListMap深入分析(转)
Java多线程之ConcurrentSkipListMap深入分析 一.前言 concurrentHashMap与ConcurrentSkipListMap性能测试 在4线程1.6万数据的条件下, ...
- 【C#】线程之Parallel
在一些常见的编程情形中,使用任务也许能提升性能.为了简化变成,静态类System.Threading.Tasks.Parallel封装了这些常见的情形,它内部使用Task对象. Parallel.Fo ...
- iOS多线程之GCD小记
iOS多线程之GCD小记 iOS多线程方案简介 从各种资料中了解到,iOS中目前有4套多线程的方案,分别是下列4中: 1.Pthreads 这是一套可以在很多操作系统上通用的多线程API,是基于C语言 ...
随机推荐
- 【sqli-labs】 less39 GET -Stacked Query Injection -Intiger based (GET型堆叠查询整型注入)
http://192.168.136.128/sqli-labs-master/Less-39/?id=1;insert into users(id,username,password) values ...
- vue货币格式化组件、局部过滤功能以及全局过滤功能
一.在这里介绍一个vue的时间格式化插件: moment 使用方法: .npm install moment --save. 2 定义时间格式化全局过滤器 在main.js中 导入组件 import ...
- BZOJ 1645: [Usaco2007 Open]City Horizon 城市地平线 扫描线 + 线段树 + 离散化
Code: #include<cstdio> #include<algorithm> #include<string> #define maxn 1030000 # ...
- freemarker使用map替换字符串中的值demo2
package demo01; import java.io.IOException;import java.io.OutputStreamWriter;import java.io.StringWr ...
- eas之EntityViewInfo对象mainQuery中查询条件
EntityViewInfo对象mainQuery中查询条件: 添加查询字段:(Sql语句中的selectz子句内容) SelecttorItemCollection sic=new Sele ...
- 如何解决windows docker共享目录不支持符号链接(do not support symlinks)?
windows使用docker toolbox,搭建前端开发环境时,在共享目录使用npm安装前端依赖时,发现报错,无法使用符号连接. 这里有一个帖子专门讨论这个问题,感兴趣可以看一下: https:/ ...
- salt 批量添加route路由
安装net-tools包 因为其余机器没有网络,使用rpm包安装,并添加缺省路由. [root@web1 base]# tree . ├── add-route.sls ├── files │ └ ...
- 爬虫系列(六) 用urllib和re爬取百度贴吧
这篇文章我们将使用 urllib 和 re 模块爬取百度贴吧,并使用三种文件格式存储数据,下面先贴上最终的效果图 1.网页分析 (1)准备工作 首先我们使用 Chrome 浏览器打开 百度贴吧,在输入 ...
- Travel Card
Travel Card time limit per test 2 seconds memory limit per test 256 megabytes input standard input o ...
- elasticsearch 文档阅读笔记(三)
文档 elasticsearch是通过document的形式存储数据的,个人理解文档就是一条数据一个对象 我们添加索引文档中不仅包含了数据还包含了元数据 比如我们为一个数据添加索引 文档中不仅有jso ...