使用RestSharp 库消费Restful Service 中介绍了一个开源的Http Client库RestSharp。在ASP.NET MVC 4中也带来.NET框架中的Http Client。它提供了一个灵活的、可扩展的API来访问一切通过HTTP公开的RESTful服务。HttpClient是ASP.NET Web API 的一部分,直接包含在.NET 4.5中,也可以单独安装ASP.NET MVC4,可以通过Nuget包获取,包里面包含以下3部分:
- System.Net.Http: The main NuGet package providing the basic HttpClient and related classes
- System.Net.Http.Formatting: Adds support for serialization, deserialization as well as for many additional features building on top of System.Net.Http
- System.Json: Adds support for JsonVaue which is a mechanism for reading and manipulating JSON documents
HttpClient是接收HttpResponseMessages和发送HttpRequestMessages的主要类,如果你习惯了使用WebClient或者是HttpWebRequest, 需要注意HttpClient和他们不同的地方:
1、在HttpClient实例上配置扩展,设置默认的头部,取消未完成的请求和更多的设置。
2、你通过一个单一的HttpClient实例,它有自己的连接池。
3、HttpClients不与特定的HTTP服务器绑定,你可以使用相同的HttpClient实例提交任何HTTP请求。
4、你可以用HttpClient为特定的站点创建特殊的Client
5、HttpClient采用新的型模式处理异步请求使它更容易管理和协调更多的请求。
下面我们看下具体的代码, MSDN code gallery 有个很详细Get操作的示例,这个示例是向World Bank Data Web API 发送一个Get请求,获取到Json格式的数据
namespace WorldBankSample
{
/// <summary>
/// Sample download list of countries from the World Bank Data sources at http://data.worldbank.org/
/// </summary>
class Program
{
static string _address = "http://api.worldbank.org/countries?format=json";
static void Main(string[] args)
{
// Create an HttpClient instance
HttpClient client = new HttpClient();
// Send a request asynchronously continue when complete
client.GetAsync(_address).ContinueWith(
(requestTask) =>
{
// Get HTTP response from completed task.
HttpResponseMessage response = requestTask.Result;
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as JsonValue and write out top facts for each country
response.Content.ReadAsAsync<JsonArray>().ContinueWith(
(readTask) =>
{
Console.WriteLine("First 50 countries listed by The World Bank...");
foreach (var country in readTask.Result[1])
{
Console.WriteLine(" {0}, Country Code: {1}, Capital: {2}, Latitude: {3}, Longitude: {4}",
&nbs
[1] [2] [3] [4] 下一页

[
asp-net]
ASP.NET 2.0运行时简要分析 (佚名,04-19)
> ASP.NET 2.0运行时简要分析 概述:本文基于ASP.NET 2.0的源代码,对ASP.NET 2.0运行时进行了简要的分析,希望能帮助你理解ASP.NET 2.0中请求处理过程及页面编译模型。关键字:ASP.NET 2.0运行时,原理,请求处理,页面编译,ASP.……

[
asp-net]
关于AspNetPager 采用URL分页时 执行两次绑定的解决办 (佚名,08-19)
Body> 先看代码: <!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/1 <abw:AspNetPage……

[
asp-net]
将不确定变为确定~程序是否真的Dispose了 (佚名,05-09)
Body> 首先将来说一下Dispose是什么东西吧,对于我们使用非托管的资源时,需要自己去实现Dispose这个方法,它的含义就是释放使用的内存空间。 例如Stream这个类型,它就是一个非托管类型,它会实现一个IDisposable接口,来实现Dispose方法 像Trans……

[
asp-net]
Datalist嵌套以及属性生成器和页面样式 (佚名,09-10)
Body> 要实现的页面效果是:1.页面添加数据绑定控件(在ddlBigType里嵌套了ddlSmallType)代码 <!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.Cod……

[
asp-net]
Web系统中关于Postback与页面离开的分辨 (佚名,08-11)
> Web系统中关于Postback与页面离开的分辨 大家在使用Asp.net开发应用系统时,有时会存在这样的场景,当页面离开时需要清空Session等等一系列的后序操作。 如果大家使用后台代码清空S……