HttpClient介紹
使用RestSharp 庫(kù)消費(fèi)Restful Service 中介紹了一個(gè)開源的Http Client庫(kù)RestSharp。在ASP.NET MVC 4中也帶來(lái).NET框架中的Http Client。它提供了一個(gè)靈活的、可擴(kuò)展的API來(lái)訪問一切通過HTTP公開的RESTful服務(wù)。HttpClient是ASP.NET Web API 的一部分,直接包含在.NET 4.5中,也可以單獨(dú)安裝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和發(fā)送HttpRequestMessages的主要類,如果你習(xí)慣了使用WebClient或者是HttpWebRequest, 需要注意HttpClient和他們不同的地方:
1、在HttpClient實(shí)例上配置擴(kuò)展,設(shè)置默認(rèn)的頭部,取消未完成的請(qǐng)求和更多的設(shè)置。
2、你通過一個(gè)單一的HttpClient實(shí)例,它有自己的連接池。
3、HttpClients不與特定的HTTP服務(wù)器綁定,你可以使用相同的HttpClient實(shí)例提交任何HTTP請(qǐng)求。
4、你可以用HttpClient為特定的站點(diǎn)創(chuàng)建特殊的Client
5、HttpClient采用新的型模式處理異步請(qǐng)求使它更容易管理和協(xié)調(diào)更多的請(qǐng)求。
下面我們看下具體的代碼, MSDN code gallery 有個(gè)很詳細(xì)Get操作的示例,這個(gè)示例是向World Bank Data Web API 發(fā)送一個(gè)Get請(qǐng)求,獲取到Json格式的數(shù)據(jù)
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();
}
}
}
下面介紹一個(gè)發(fā)送Post 請(qǐng)求的示例,示例代碼使用默認(rèn)創(chuàng)建的ASP.NET Web API模板項(xiàng)目:
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);
});
});
上面代碼首先是創(chuàng)建一個(gè)HttpClient實(shí)例,設(shè)置要Post的數(shù)據(jù)的格式,然后調(diào)用HttpClient的異步請(qǐng)求,獲取到的是一個(gè)HttpResponseMessage實(shí)例,可以在這個(gè)實(shí)例中檢查請(qǐng)求的狀態(tài),調(diào)用的是一個(gè)擴(kuò)展方法EnsureSuccessStatusCode,如果不是HttpStatusCode.OK,就會(huì)拋出一個(gè)異常。通過HttpResponseMessage的Content屬性獲取HttpContent,HttpContent有一些方法輔助處理接收的內(nèi)容。
對(duì)應(yīng)于使用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);
}
上面是通過代碼發(fā)送的Http請(qǐng)求,也可以用Fiddlers來(lái)驗(yàn)證請(qǐng)求,例如:
歡迎大家掃描下面二維碼成為我的客戶,扶你上云



浙公網(wǎng)安備 33010602011771號(hào)