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:其他项目引用(可 ...
随机推荐
- struts2、hibernate的知识点
以下内容是我在复习struts2.hibernate和spring的时候记下得到,部分书上找不到的内容来自网络 以下是网络部分的原文网站: http://blog.csdn.net/frankaqi/ ...
- ZendFramework-2.4 源代码 - 关于MVC - Controller层
// 1.控制器管理器 class ServiceManager implements ServiceLocatorInterface { public function __construct(Co ...
- 678. Valid Parenthesis String
https://leetcode.com/problems/valid-parenthesis-string/description/ 这个题的难点在增加了*,*可能是(也可能是).是(的前提是:右边 ...
- BFS:CF356C-Compartments
C. Compartments time limit per test 1 second memory limit per test 256 megabytes input standard inpu ...
- SJTU 1077 加分二叉树
http://acm.sjtu.edu.cn/OnlineJudge/problem/1077 题意: 设一个n个节点的二叉树tree的中序遍历为(l,2,3,…,n),其中数字1,2,3…,n为节点 ...
- dp专练
dp练习. codevs 1048 石子归并 区间dp #include<cstdio> #include<algorithm> #include<cstring> ...
- UVa 1649 Binomial coefficients 数学
题意: \(C(n, k) = m(2 \leq m \leq 10^{15})\),给出\(m\)求所有可能的\(n\)和\(k\). 分析: 设\(minK = min(k, n - k)\),容 ...
- 【bzoj3339】Rmq Problem
[bzoj3339]Rmq Problem Description Input Output Sample Input 7 50 2 1 0 1 3 21 32 31 43 62 7 Sample ...
- getsupportfragmentmanager 没有这个方法
让activity继承自fragmentactivity就行了.
- PyInstaller打包python脚本
用python写的工具写好了,想打包然后发给测试同事使用,最后选择了PyInstaller,支持Windows.Linux.OS X,支持打包成一个文件夹或单个EXE文件. 我是直接在线安装的,在 ...