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之后:

  1. using Microsoft.VisualStudio.TestTools.UnitTesting;
  2. using TestMvc;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10.  
  11. namespace TestMvc.Tests
  12. {
  13. [TestClass()]
  14. public class ResultFilterTests
  15. {
  16. [TestMethod()]
  17. public void OnResultExecutedTest()
  18. {
  19.  
  20. Assert.Fail();
  21. }
  22. }
  23.  
  24. class Test
  25. {
  26.  
  27. /// <summary>
  28. /// HttpClient实现Get请求
  29. /// </summary>
  30. static async void dooGet()
  31. {
  32. string url = "http://localhost:52824/api/register?id=1&leval=5";
  33. //创建HttpClient(注意传入HttpClientHandler)
  34. var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
  35.  
  36. using (var http = new HttpClient(handler))
  37. {
  38. //await异步等待回应
  39. var response = await http.GetAsync(url);
  40. //确保HTTP成功状态值
  41. response.EnsureSuccessStatusCode();
  42.  
  43. //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
  44. Console.WriteLine(await response.Content.ReadAsStringAsync());
  45. }
  46. }
  47. /// <summary>
  48. /// HttpClient实现Post请求
  49. /// </summary>
  50. static async void dooPost()
  51. {
  52. string url = "http://localhost:52824/api/register";
  53. var userId = "";
  54. //设置HttpClientHandler的AutomaticDecompression
  55. var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
  56. //创建HttpClient(注意传入HttpClientHandler)
  57. using (var http = new HttpClient(handler))
  58. {
  59. //使用FormUrlEncodedContent做HttpContent
  60. var content = new FormUrlEncodedContent(new Dictionary<string, string>()
  61. {
  62. {"", userId}//键名必须为空
  63. });
  64.  
  65. //await异步等待回应
  66.  
  67. var response = await http.PostAsync(url, content);
  68. //确保HTTP成功状态值
  69. response.EnsureSuccessStatusCode();
  70. //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
  71. Console.WriteLine(await response.Content.ReadAsStringAsync());
  72. }
  73.  
  74. }
  75.  
  76. /// <summary>
  77. /// HttpClient实现Put请求
  78. /// </summary>
  79. static async void dooPut()
  80. {
  81. var userId = "";
  82. string url = "http://localhost:52824/api/register?userid=" + userId;
  83.  
  84. //设置HttpClientHandler的AutomaticDecompression
  85. var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
  86. //创建HttpClient(注意传入HttpClientHandler)
  87. using (var http = new HttpClient(handler))
  88. {
  89. //使用FormUrlEncodedContent做HttpContent
  90. var content = new FormUrlEncodedContent(new Dictionary<string, string>()
  91. {
  92. {"", "数据"}//键名必须为空
  93. });
  94.  
  95. //await异步等待回应
  96.  
  97. var response = await http.PutAsync(url, content);
  98. //确保HTTP成功状态值
  99. response.EnsureSuccessStatusCode();
  100. //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip)
  101. Console.WriteLine(await response.Content.ReadAsStringAsync());
  102. }
  103.  
  104. }
  105. }
  106. }

httpclient与webapi的更多相关文章

  1. httpclient 调用WebAPI

    1.创建webapi项目,提供接口方法如下: /// <summary> /// 获取租户.位置下的所有传感器 /// </summary> /// <returns&g ...

  2. WebClient和HttpClient, 以及webapi上传图片

    httppost请求. applicationkey/x-www-form-urlencoded请求: Email=321a&Name=kkfewwebapi里面, 如果用实体, 能接受到. ...

  3. C# HttpClient请求Webapi帮助类

    引用 Newtonsoft.Json // Post请求 public string PostResponse(string url,string postData,out string status ...

  4. 使用HttpClient调用WebAPI接口,含WebAPI端示例

    API端: using log4net; using System; using System.Collections.Generic; using System.IO; using System.L ...

  5. HttpClient调用webApi时注意的小问题

    HttpClient client = new HttpClient(); client.BaseAddress = new Uri(thisUrl); client.GetAsync("a ...

  6. HttpClient 请求WebApi

    HttpClient client = new HttpClient(); client.BaseAddress = new Uri(ConfigurationManager.AppSettings[ ...

  7. HttpClient 调用WebAPI时,传参的三种方式

    public void Post() { //方法一,传json参数 var d = new { username = " ", password = " ", ...

  8. C#工具:利用HttpClient调用WebApi

    可以利用HttpClient来进行Web Api的调用.由于WebA Api的调用本质上就是一次普通的发送请求与接收响应的过程, 所有HttpClient其实可以作为一般意义上发送HTTP请求的工具. ...

  9. 封装WebAPI客户端,附赠Nuget打包上传VS拓展工具

    一.前言 上篇< WebAPI使用多个xml文件生成帮助文档 >有提到为什么会出现基于多个xml文件生成帮助文档的解决方案,因为定义的模型可能的用处有: 1:单元测试 2:其他项目引用(可 ...

随机推荐

  1. struts2、hibernate的知识点

    以下内容是我在复习struts2.hibernate和spring的时候记下得到,部分书上找不到的内容来自网络 以下是网络部分的原文网站: http://blog.csdn.net/frankaqi/ ...

  2. ZendFramework-2.4 源代码 - 关于MVC - Controller层

    // 1.控制器管理器 class ServiceManager implements ServiceLocatorInterface { public function __construct(Co ...

  3. 678. Valid Parenthesis String

    https://leetcode.com/problems/valid-parenthesis-string/description/ 这个题的难点在增加了*,*可能是(也可能是).是(的前提是:右边 ...

  4. BFS:CF356C-Compartments

    C. Compartments time limit per test 1 second memory limit per test 256 megabytes input standard inpu ...

  5. SJTU 1077 加分二叉树

    http://acm.sjtu.edu.cn/OnlineJudge/problem/1077 题意: 设一个n个节点的二叉树tree的中序遍历为(l,2,3,…,n),其中数字1,2,3…,n为节点 ...

  6. dp专练

    dp练习. codevs 1048 石子归并 区间dp #include<cstdio> #include<algorithm> #include<cstring> ...

  7. UVa 1649 Binomial coefficients 数学

    题意: \(C(n, k) = m(2 \leq m \leq 10^{15})\),给出\(m\)求所有可能的\(n\)和\(k\). 分析: 设\(minK = min(k, n - k)\),容 ...

  8. 【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 ...

  9. getsupportfragmentmanager 没有这个方法

    让activity继承自fragmentactivity就行了.

  10. PyInstaller打包python脚本

    用python写的工具写好了,想打包然后发给测试同事使用,最后选择了PyInstaller,支持Windows.Linux.OS X,支持打包成一个文件夹或单个EXE文件.   我是直接在线安装的,在 ...