多线程之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】 less15 POST - Blind- Boolian/time Based - Single quotes (基于bool/时间的单引号POST型盲注)
错误不回显了 构造永真登陆 登陆成功了 虽然登陆成功了,但是数据库的数据还么有爆出来 构造一下用户名 ' or length(database())=8# 如果数据库名的长度不等于8,登陆会失败 猜测 ...
- Arduino LM35温度检测
一. 接线原理图 二.实物图 三.代码例子
- Redis 通用key操作命令
1.在redis里面允许模糊查询key,有3个通配符:*,?,[]. *:通配任意字符 ?:通配单个字符 []:通配中括号内的某个字符 例如: 2.randomKey 随机返回所有key中的某个 3. ...
- BZOJ 1738: [Usaco2005 mar]Ombrophobic Bovines 发抖的牛 网络流 + 二分 + Floyd
Description FJ's cows really hate getting wet so much that the mere thought of getting caught in the ...
- loadrunner安装方法
1.loadrunner安装网盘地址: http://pan.baidu.com/s/1hrP6mDQ 一般会提示:“vc2005_sp1_with_atl_fix_redist 2.确认时提示缺少 ...
- 【剑指Offer】52、正则表达式匹配
题目描述: 请实现一个函数用来匹配包括'.'和'*'的正则表达式.模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次). 在本题中,匹配是指字符串的所有字符匹 ...
- ext4的一些特性
delalloc介绍 delalloc是ext4下的一个新特性,延迟分配技术Delay Allocation. 实现原理为: Buffer Write时数据会被保存到page cache中,但是系统并 ...
- Layui 行点击追加元素效果
/** * 单击事件 * @param obj */var dom;var state;WarningIllegalIntime.onRowClick=function(obj) { console. ...
- npm命令及解释
npm是Node Package Manager,也就是长说的NPM包管理器. 一般安装node.js就会一起安装. npm install npm install XXX //表示安装模块, ...
- c++0x11新特性:delete删除函数
c_plus_plus_0x11.cpp: // c_plus_plus_0x11.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #inc ...