System.Net.Http for Silverlight

简介:

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 实体正文, 如下图所示:

HttpContent Class Diagrams

此外, System.Net.Http 对 HTTP 消息的处理采用了职责链模式, 这里有一遍不错的介绍, 这里就不再多说了。

Silverlight 版本的 System.Net.Http

System.Net.Http 最早和 Asp.Net Mvc4 同时出现, 可以在 .Net 4.0 中使用。 随着 .Net 4.5 的发布, System.Net.Http 正式成为 .Net 基础类库, 目前已经可以在 .Net 4.0/4.5 、 Windows Phone 、 以及 Windows Store App 中使用, 唯独没有发布 Silverlight 版本的 System.Net.Http。 更加悲催的是, 随着 Xamarin 2.0 的发布, Xamarin.Android 和 Xamarin.iOS 居然也开始支持 System.Net.Http , 真是让做 Silverlight 开发的码农心寒。

幸好, .Net 有开源的实现, 那就是 Mono , 其中有大量开源的 .Net 基础类实现, 在 Mono 3.x 版本中, 就有开源的 System.Net.Http , Xamarin 发布的 Android 和 iOS 版本的 System.Net.Http 就是源自 Mono 的, 既然 Android 和 iOS 可以, 相信 Silverlight 也肯定可以, 抱着试试看的态度, 下载了 Mono 下的 System.Net.Http 源代码, 并整理成了一个 Silverlight 项目。 经过一番努力, Silverlight 版本的 System.Net.Http 终于可以使用了, GitHub 项目地址: https://github.com/beginor/System_Net_Http , 欢迎围观。

由于 Silverlight 平台对 HTTP 的限制, 移除了部分功能, 例如 Proxy 、 AllowAutoRedirect 、 PreAuthenticate 以及 KeepAlive 设置等, 这些都是 Silverlight 不支持的。

对于 Silverlight 的 BrowserHttp , 仅仅支持 GET 和 POST 方法, 示例代码如下:

HttpClient client = new HttpClient {
   BaseAddress = new Uri("http://localhost:8080/HttpTestWeb/api/")
};

// Get string from server
client.GetStringAsync("browserhttp/").ContinueWith(t => {
   if (t.IsFaulted) {
      // report error here
      //Application.Current.ReportError(t.Exception.GetBaseException());
   } else {
      string txt = t.Result;
      //Assert.IsFalse(string.IsNullOrEmpty(txt));
   }
});

// Post form data to server
var param = new Dictionary<string, string> {
   {"Name", "Client Post"},
   {"Age", "1"},
   {"Birthday", DateTime.Today.ToString("s")}
};
client.PostAsync("browserhttp/", new FormUrlEncodedContent(param)).ContinueWith(t => {
   if (t.IsFaulted) {
      // report error here
      // Application.Current.ReportError(t.Exception.GetBaseException());
   } else {
      HttpResponseMessage response = t.Result;
      //Assert.IsTrue(response.EnsureSuccessStatusCode);
   }
});
AI 代码解读

对于 ClientHttp , 除了 GET 和 POST 之外, 还支持 PUT 和 DELETE (其它的 HTTP 方法也可能支持, 未测试), 示例代码如下:

// PUT to update
var param = new Dictionary<string, string> {
   {"Id", "1" },
   {"Name", "Client Post"},
   {"Age", "1"},
   {"Birthday", DateTime.Today.ToString("s")}
};
client.PutAsync("clienthttp/1", new FormUrlEncodedContent(param)).ContinueWith(t => {
   if (t.IsFaulted) {
      // report error here
      // Application.Current.ReportError(t.Exception.GetBaseException());
   } else {
      HttpResponseMessage response = t.Result;
      //Assert.IsTrue(response.EnsureSuccessStatusCode);
   }
});

// DELETE
client.DeleteAsync("clienthttp/1").ContinueWith(t => {
   if (t.IsFaulted) {
      // report error here
      // Application.Current.ReportError(t.Exception.GetBaseException());
   } else {
      HttpResponseMessage response = t.Result;
      //Assert.IsTrue(response.EnsureSuccessStatusCode);
   }
});
AI 代码解读

支持职责链模式的 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;
   }
}
AI 代码解读

使用起来也是非常简单的:

var customHandler = new CustomProcessingHandler {
    InnerHandler = new HttpClientHandler()
};
var client = new HttpClient(customHandler, true) {
    BaseAddress = new Uri("http://localhost:8080/HttpTestWeb/api/")
};
AI 代码解读

参考资料:

张志敏所有文章遵循创作共用版权协议,要求署名、非商业 、保持一致。在满足创作共用版权协议的基础上可以转载,但请以超链接形式注明出处。

本博客已经迁移到 GitHub , 围观地址: http://beginor.github.io/

本文转自张志敏博客园博客,原文链接:http://www.cnblogs.com/beginor/archive/2013/04/14/3019807.html ,如需转载请自行联系原作者
目录
打赏
0
0
0
0
66
分享
相关文章
如何让你的.NET WebAPI程序支持HTTP3?
如何让你的.NET WebAPI程序支持HTTP3?
119 2
如何让你的.NET WebAPI程序支持HTTP3?
.NET 8新特性:使用ConfigurePrimaryHttpMessageHandler定制HTTP请求
在.NET 8中,通过`ConfigurePrimaryHttpMessageHandler`方法,开发者能更精细地控制HTTP请求,这对于构建高效爬虫尤为重要。此特性支持定制代理IP、管理Cookie与User-Agent,结合多线程技术,有效应对网络限制及提高数据采集效率。示例代码展示了如何设置代理服务器、模拟用户行为及并发请求,从而在遵守网站规则的同时,实现快速稳定的数据抓取。
116 0
.NET 8新特性:使用ConfigurePrimaryHttpMessageHandler定制HTTP请求
|
7月前
|
Go
Go中 net/http 使用
Go中 net/http 使用
49 0
go的net/http有哪些值得关注的细节? 2
go的net/http有哪些值得关注的细节?
118 0
C# .NET面试系列八:ADO.NET、XML、HTTP、AJAX、WebService
## 第二部分:ADO.NET、XML、HTTP、AJAX、WebService #### 1. .NET 和 C# 有什么区别? .NET(通用语言运行时): ```c# 定义:.NET 是一个软件开发框架,提供了一个通用的运行时环境,用于在不同的编程语言中执行代码。 作用:它为多语言支持提供了一个统一的平台,允许不同的语言共享类库和其他资源。.NET 包括 Common Language Runtime (CLR)、基础类库(BCL)和其他工具。 ``` C#(C Sharp): ```c# 定义: C# 是一种由微软设计的面向对象的编程语言,专门为.NET 平台开发而创建。 作
378 2
go的net/http有哪些值得关注的细节? 4
go的net/http有哪些值得关注的细节?
138 0
go的net/http有哪些值得关注的细节? 1
go的net/http有哪些值得关注的细节?
94 0
go的net/http有哪些值得关注的细节? 3
go的net/http有哪些值得关注的细节?
184 0
.net调用http服务
前段时间刚将一个需求融入到OA产品中,又遇到了另一个问题,通过一个.net平台调用写好的服务,进行http请求,来实现两个项目之间信息的流转。
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等