zoukankan      html  css  js  c++  java
  • 对于System.Net.Http的学习(一)——System.Net.Http 简介

    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的基本使用方法,示例代码如下:

    //声明HttpClient
    
        HttpClient client = new HttpClient
    
            {
    
                BaseAddress = new Uri("http://www.163.com")
    
            };
    
    //多线程中跨线程进行信息显示委托
    
    public delegate void ShowMsgDelegate(string text);
    
        public void ShowMsgText(string text)
    
        {
    
             txtMsg.Text=text;         
    
    }
    
    //信息显示
    
        private void ShowMessage(string  msg)
    
        {
    
            if (this.InvokeRequired)
    
            {
    
                this.Invoke(new ShowMsgDelegate(ShowMsgText), msg);
    
            }
    
            else
    
            {
    
                ShowMsgText(msg);
    
            }
    
        }
    
     
    
    // Get form data to server
    
     
    
            private void btnGet_Click(object sender, EventArgs e)
    
            {
    
                // Get string from server
    
                client.GetStringAsync("browserhttp/").ContinueWith(t =>
    
                {               
    
                    if (t.IsFaulted)
    
                    {
    
                        ShowMessage("返回信息错误:" + t.Result);                
    
                    }
    
                    else
    
                    {
    
                                        ShowMessage("成功:" + t.Result);
    
                       }
    
                });
    
            }
    
     
    
           
    
     
    
    // Post form data to server
    
     
    
        private void btnPost_Click(object sender, EventArgs e)
    
        {
    
            var param = new Dictionary<string, string> {
    
       {"Name", "TOM Post"},
    
       {"Age", "11"},
    
       {"Birthday", DateTime.Now.ToString("yyyyMMdd")}
    
            };
    
     
    
            client.PostAsync("browserhttp/", new FormUrlEncodedContent(param)).ContinueWith(t =>
    
            {
    
                ShowMsgDelegate showmsg = new ShowMsgDelegate(ShowMsgText);
    
                if (t.IsFaulted)
    
                {
    
                    ShowMessage("返回信息错误:" + t.Result);
    
                
    
                }
    
                else
    
                {
    
                    HttpResponseMessage response = t.Result;
    
                    ShowMessage(response.StatusCode.ToString());
    
                            }
    
            });
    
     
    
        }
    
    // PUT to update
    
    private void btnPut_Click(object sender, EventArgs e)
    
        {
    
            var param = new Dictionary<string, string> {
    
       {"Id", "10" },
    
       {"Name", "Tom Post"},
    
       {"Age", "10"},
    
       {"Birthday", DateTime.Now.ToString("yyyyMMdd")}
    
    };
    
            client.PutAsync("clienthttp/1", new FormUrlEncodedContent(param)).ContinueWith(t =>
    
            {
    
                if (t.IsFaulted)
    
                {
    
                    ShowMessage("返回信息错误:" + t.Result);              
    
                }
    
                else
    
                {
    
                    HttpResponseMessage response = t.Result;
    
                    ShowMessage(response.StatusCode.ToString());
    
                  }
    
            });
    
        }
    
      
    
    // DELETE 
    
     
    
        private void btnDel_Click(object sender, EventArgs e)
    
        {
    
            client.DeleteAsync("clienthttp/1").ContinueWith(t =>
    
            {
    
                if (t.IsFaulted)
    
                {
    
                    ShowMessage("返回信息错误:" + t.Result);
    
               
    
                }
    
                else
    
                {
    
                    HttpResponseMessage response = t.Result;
    
                    ShowMessage(response.StatusCode.ToString());
    
                  }
    
            });
    
    }
    
     

      支持职责链模式的 MessageProcessingHandler ,MessageProcessingHandler - 一种基本的 HTTP 消息处理程序。这是最容易进行派生的处理程序,应该作为大多数自定义处理程序的起点。 自已定义了一个新的MessageProcessingHandler处理程序,如下面的示例代码所示:

    public class CustomProcessingHandler : MessageProcessingHandler {
    
     
    
       protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken) {
    
          if (request.Method != HttpMethod.Get && request.Method != HttpMethod.Post) {
    
             request.Headers.TryAddWithoutValidation("RequestMethod", request.Method.Method);
    
             request.Method = HttpMethod.Post;
    
          }
    
          return request;
    
       }
    
     
    
       protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken) {
    
          var request = response.RequestMessage;
    
          if (request.Headers.Contains("RequestMethod")) {
    
             IEnumerable<string> values;
    
             if (request.Headers.TryGetValues("RequestMethod", out values)) {
    
                request.Method = new HttpMethod(values.First());
    
             }
    
          }
    
          return response;
    
       }
    
    }
    
      使用起来也是非常简单的:
    
      private void btnCustom_Click(object sender, EventArgs e)
    
            {
    
                var customHandler = new CustomProcessingHandler
    
                {
    
                    InnerHandler = new HttpClientHandler()
    
                };
    
                
    
                var client = new HttpClient(customHandler, true)
    
                {
    
                    BaseAddress = new Uri("http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl")
    
                };
    
                var task = client.GetAsync(client.BaseAddress);
    
                task.Result.EnsureSuccessStatusCode();
    
                HttpResponseMessage response = task.Result;
    
                txtStatusCode.Text = response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine;
    
                txtStatusText.Text = "请求返回结果如下 ...";
    
                var result = response.Content.ReadAsStringAsync();         
    
                txtMsg.Text = result.Result; ;
    
     
    
            }
  • 相关阅读:
    Server requested plaintext password but ‘client plaintext auth’ is disabled
    LDAP目录树中常见的关键字
    LINUX下让一个用户添加进多个组中
    CentOS5.6下samba+ldap+smbldaptools的安装
    解决configure: error: Cannot find pam headers. Please check if your system is ready for pam module development
    解决configure: error: C++ compiler cannot create executables问题
    IE中拖动DOM元素的例子
    请确保此代码文件中定义的类与“inherits”属性匹配,并且该类扩展的基类(例如Page 或UserControl)是正确的。
    DOM中的高级事件处理
    好导网(推荐)
  • 原文地址:https://www.cnblogs.com/chillsrc/p/3439215.html
Copyright © 2011-2022 走看看