HttpClient介绍
2016-04-28 17:43
459 查看
http://www.cnblogs.com/shanyou/archive/2012/03/21/2410739.html
使用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}",
country.Value["name"],
country.Value["iso2Code"],
country.Value["capitalCity"],
country.Value["latitude"],
country.Value["longitude"]);
}
});
});
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
}
}
下面介绍一个发送Post 请求的示例,示例代码使用默认创建的ASP.NET Web API模板项目:
public class ValuesController : ApiController
{
// GET /api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET /api/values/5
public string Get(int id)
{
return "value";
}
// POST /api/values
public string Post(string value)
{
return value;
}
// PUT /api/values/5
public void Put(int id, string value)
{
}
// DELETE /api/values/5
public void Delete(int id)
{
}
}
使用HttpClient示例的代码如下:
string serviceAddress = "http://localhost:2650/api/values";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceAddress);
request.Method = "POST";
request.ContentType = "application/json";
string strContent = @"{ ""value"": ""test""}" ;
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(strContent);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader dataStream = new StreamReader(response.GetResponseStream()))
{
var result = dataStream.ReadToEnd();
Console.WriteLine(result);
}
Uri serviceReq = new Uri(serviceAddress);
HttpClient client = new HttpClient();
HttpContent content = new StringContent(@"{ ""value"": ""test""}");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Send a request asynchronously continue when complete
client.PostAsync(serviceReq, content).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<string>().ContinueWith(
(readTask) =>
{
Console.WriteLine(readTask.Result);
});
});
上面代码首先是创建一个HttpClient实例,设置要Post的数据的格式,然后调用HttpClient的异步请求,获取到的是一个HttpResponseMessage实例,可以在这个实例中检查请求的状态,调用的是一个扩展方法EnsureSuccessStatusCode,如果不是
对应于使用HttpWebRequest的示例如下:
string serviceAddress = "http://localhost:2650/api/values";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceAddress);
request.Method = "POST";
request.ContentType = "application/json";
string strContent = @"{ ""value"": ""test""}" ;
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(strContent);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader dataStream = new StreamReader(response.GetResponseStream()))
{
var result = dataStream.ReadToEnd();
Console.WriteLine(result);
}
上面是通过代码发送的Http请求,也可以用Fiddlers来验证请求,例如:
使用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}",
country.Value["name"],
country.Value["iso2Code"],
country.Value["capitalCity"],
country.Value["latitude"],
country.Value["longitude"]);
}
});
});
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
}
}
下面介绍一个发送Post 请求的示例,示例代码使用默认创建的ASP.NET Web API模板项目:
public class ValuesController : ApiController
{
// GET /api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET /api/values/5
public string Get(int id)
{
return "value";
}
// POST /api/values
public string Post(string value)
{
return value;
}
// PUT /api/values/5
public void Put(int id, string value)
{
}
// DELETE /api/values/5
public void Delete(int id)
{
}
}
使用HttpClient示例的代码如下:
string serviceAddress = "http://localhost:2650/api/values";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceAddress);
request.Method = "POST";
request.ContentType = "application/json";
string strContent = @"{ ""value"": ""test""}" ;
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(strContent);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader dataStream = new StreamReader(response.GetResponseStream()))
{
var result = dataStream.ReadToEnd();
Console.WriteLine(result);
}
Uri serviceReq = new Uri(serviceAddress);
HttpClient client = new HttpClient();
HttpContent content = new StringContent(@"{ ""value"": ""test""}");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Send a request asynchronously continue when complete
client.PostAsync(serviceReq, content).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<string>().ContinueWith(
(readTask) =>
{
Console.WriteLine(readTask.Result);
});
});
上面代码首先是创建一个HttpClient实例,设置要Post的数据的格式,然后调用HttpClient的异步请求,获取到的是一个HttpResponseMessage实例,可以在这个实例中检查请求的状态,调用的是一个扩展方法EnsureSuccessStatusCode,如果不是
HttpStatusCode.OK,就会抛出一个异常。通过HttpResponseMessage的Content属性获取HttpContent,HttpContent有一些方法辅助处理接收的内容。
对应于使用HttpWebRequest的示例如下:
string serviceAddress = "http://localhost:2650/api/values";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceAddress);
request.Method = "POST";
request.ContentType = "application/json";
string strContent = @"{ ""value"": ""test""}" ;
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(strContent);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader dataStream = new StreamReader(response.GetResponseStream()))
{
var result = dataStream.ReadToEnd();
Console.WriteLine(result);
}
上面是通过代码发送的Http请求,也可以用Fiddlers来验证请求,例如:
相关文章推荐
- 安装protocolbuffer详解 原创: http://cq520.iteye.com/blog/2024739
- 个人电脑如何搭建服务器?或远程连接
- 机器学习算法----贝叶斯网络
- 图解HTTPS
- MicroERP如何配置网络应用
- MicroERP如何配置网络应用
- 解决阿里云VPC网络下面ECS不能指定高于X.X.X.247私有IP地址的方法
- 20159217《网络攻防实践》第九周学习总结
- Unity网络教程翻译(一)从零开始编写一个网络游戏
- IOS中UIImageView使用网络图片
- 判断网络请求数据是否是json
- QT-基于TCP的网络通信
- xcode 7.0后,网络加载失败,以及本地服务器资源加载失败解决
- spring mvc 数据绑定问题 提交表单提示HTTP status 400, The request sent by the client was syntactically incorrect
- Ubuntu浏览器无法上网 QQ等软件正常联网问题解决
- Web编程的核心是HTTP协议
- Android Volley完全解析(二),使用Volley加载网络图片
- iOS开发网络篇—文件的上传
- iOS开发网络篇—数据安全
- Boost C++: 网络编程1