httpclient与webapi
System.Net.Http 是微软推出的最新的 HTTP 应用程序的编程接口, 微软称之为“现代化的 HTTP 编程接口”, 主要提供如下内容:
1. 用户通过 HTTP 使用现代化的 Web Service 的客户端组件;
2. 能够同时在客户端与服务端同时使用的 HTTP 组件(比如处理 HTTP 标头和消息), 为客户端和服务端提供一致的编程模型。
命名空间 System.Net.Http 以及 System.Net.Http.Headers 提供了如下内容:
1. HttpClient 发送和接收 HTTP 请求与响应;
2. HttpRequestMessage and HttpResponseMessage 封装了 RFC 2616 定义的 HTTP 消息;
3. HttpHeaders 封装了 RFC 2616 定义的 HTTP 标头;
4. HttpClientHandler 负责生成HTTP响应消息的HTTP处理程序。
System.Net.Http 能够处理多种类型的 RFC 2616 定义的 HTTP 实体正文, 如下图所示:

此外, System.Net.Http 对 HTTP 消息的处理采用了职责链模式, 这里有一遍不错的介绍 , 这里就不再多说了。
System.Net.Http 最早是和 Asp.Net Mvc4 同时出现, 是一个第三方组件,名称是 Microsoft HTTP Client Libraries ,可以在 .Net 4.0 中使用。 随着 .Net 4.5 的发布, System.Net.Http 正式成为 .Net 基础类库, 目前已经可以在 .Net 4.0/4.5 、 Windows Phone 、 以及 Windows Store App 中使用。
HttpClient 组件类实例为一个会话发送 HTTP 请求。 HttpClient 实例设置为集合会应用于该实例执行的所有请求。 此外,每 HttpClient 实例使用自己的连接池, 隔离其他 HttpClient 实例的执行请求。 HttpClient 也是更具体的 HTTP 客户端的基类。
默认情况下,使用 HttpWebRequest 向服务器发送请求。 这一行为可通过在接受一个HttpMessageHandler实例作为参数的构造函数重载中指定不同的通道来更改。
如果需要身份验证或缓存的功能,WebRequestHandler 可使用配置项和实例传递给构造函数。 返回的处理程序传递到采用 HttpMessageHandler 参数的某构造进行返回参数传递。
如果使用 HttpClient 和相关组件类的 app 在 System.Net.Http 命名空间用于下载大量数据 (可达 50 MB 或更多),则应用程序应这些下载的流和不使用默认值缓冲区。 如果使用默认值缓冲区客户端内存使用量会非常大,可能会导致显着降低的性能。
代码使用,httpclient封装,.net4.0之后:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestMvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks; namespace TestMvc.Tests
{
[TestClass()]
public class ResultFilterTests
{
[TestMethod()]
public void OnResultExecutedTest()
{ Assert.Fail();
}
} class Test
{ /// <summary>
/// HttpClient实现Get请求
/// </summary>
static async void dooGet()
{
string url = "http://localhost:52824/api/register?id=1&leval=5";
//创建HttpClient(注意传入HttpClientHandler)
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip }; using (var http = new HttpClient(handler))
{
//await异步等待回应
var response = await http.GetAsync(url);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode(); //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
}
/// <summary>
/// HttpClient实现Post请求
/// </summary>
static async void dooPost()
{
string url = "http://localhost:52824/api/register";
var userId = "";
//设置HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
//创建HttpClient(注意传入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"", userId}//键名必须为空
}); //await异步等待回应 var response = await http.PostAsync(url, content);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode();
//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
Console.WriteLine(await response.Content.ReadAsStringAsync());
} } /// <summary>
/// HttpClient实现Put请求
/// </summary>
static async void dooPut()
{
var userId = "";
string url = "http://localhost:52824/api/register?userid=" + userId; //设置HttpClientHandler的AutomaticDecompression
var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
//创建HttpClient(注意传入HttpClientHandler)
using (var http = new HttpClient(handler))
{
//使用FormUrlEncodedContent做HttpContent
var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"", "数据"}//键名必须为空
}); //await异步等待回应 var response = await http.PutAsync(url, content);
//确保HTTP成功状态值
response.EnsureSuccessStatusCode();
//await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
Console.WriteLine(await response.Content.ReadAsStringAsync());
} }
}
}
httpclient与webapi的更多相关文章
- httpclient 调用WebAPI
1.创建webapi项目,提供接口方法如下: /// <summary> /// 获取租户.位置下的所有传感器 /// </summary> /// <returns&g ...
- WebClient和HttpClient, 以及webapi上传图片
httppost请求. applicationkey/x-www-form-urlencoded请求: Email=321a&Name=kkfewwebapi里面, 如果用实体, 能接受到. ...
- C# HttpClient请求Webapi帮助类
引用 Newtonsoft.Json // Post请求 public string PostResponse(string url,string postData,out string status ...
- 使用HttpClient调用WebAPI接口,含WebAPI端示例
API端: using log4net; using System; using System.Collections.Generic; using System.IO; using System.L ...
- HttpClient调用webApi时注意的小问题
HttpClient client = new HttpClient(); client.BaseAddress = new Uri(thisUrl); client.GetAsync("a ...
- HttpClient 请求WebApi
HttpClient client = new HttpClient(); client.BaseAddress = new Uri(ConfigurationManager.AppSettings[ ...
- HttpClient 调用WebAPI时,传参的三种方式
public void Post() { //方法一,传json参数 var d = new { username = " ", password = " ", ...
- C#工具:利用HttpClient调用WebApi
可以利用HttpClient来进行Web Api的调用.由于WebA Api的调用本质上就是一次普通的发送请求与接收响应的过程, 所有HttpClient其实可以作为一般意义上发送HTTP请求的工具. ...
- 封装WebAPI客户端,附赠Nuget打包上传VS拓展工具
一.前言 上篇< WebAPI使用多个xml文件生成帮助文档 >有提到为什么会出现基于多个xml文件生成帮助文档的解决方案,因为定义的模型可能的用处有: 1:单元测试 2:其他项目引用(可 ...
随机推荐
- 【前端_React】React小书
参考书籍:React.js 小书
- python 正则表达式与JSON字符串
目录 正则表达式 概括单字符集 匹配单字符 匹配字符集 普通字符与元字符 元字符和普通的字符的混用 数量词{整数|*|+|?} 匹配指规则的字母 贪婪模式 匹配指定长度的字符串 非贪婪模式 匹配指定长 ...
- day 71 Django基础六之ORM中的锁和事务
Django基础六之ORM中的锁和事务 本节目录 一 锁 二 事务 三 xxx 四 xxx 五 xxx 六 xxx 七 xxx 八 xxx 一 锁 行级锁 select_for_update(no ...
- mysql初始化失败的问题
首先:my.ini 配置文件中 路径需要改成自己电脑mysql解压的路径. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ...
- unknow table alarmtemp error when drop database (mysql)
Q: unknow table alarmtemp error when drop database (mysql) D: alarmtemp is table in rtmd database. ...
- Install ADDS on Windows Server 2012 R2 with PowerShell
Install ADDS on Windows Server 2012 R2 with PowerShell Posted by ethernuno on 20/04/2014 In this tut ...
- C#操作XML配置文件
代码为C#操作xml配置文件的范例类,函数SetValue用于向配置文件写入一个值,GetValue用于根据Key获取相应值。这种方法的配置文件不需要手动创建,程序在运行后会自动处理创建。 注意:1. ...
- C++ STL map容器的说明测试1
// maptest.cpp : 定义控制台应用程序的入口点.// #include "stdafx.h" /*********************************** ...
- Python+Selenium练习篇之16-自定义浏览器窗口大小
本文来学习下如何通过Selenium方法,设置符合不同测试场景浏览器窗口大小.例如,你有一台机器,最大支持1366*768,你完全可以利用这个机器测试不同分辨率下的场景. 相关测试脚本代码如下: # ...
- Python+Selenium练习篇之13-获取当前页面的URL
本文介绍如何通过webdriver方法获取当前测试页面的URL.获取当前URL有什么用处呢,一般URL可以帮助我们判断跳转的页面是否正确,或者URL中部分字段可以作为我们自动化测试脚本期待结果的一部分 ...