互聯網上關於.NET(C#)的HTTP相關的輔助類還是比較多的,這里再為大家推薦一個.NET的HTTP輔助類,它叫RestSharp。RestSharp是一個輕量的,不依賴任何第三方的組件或者類庫的Http的組件。RestSharp具有以下的優點:
- 支持.NET 3.5+,Silverlight 4, Windows Phone 7, Mono, MonoTouch, Mono for Android, Compact Framework 3.5等
- 通過NuGet方便引入到任何項目 ( Install-Package restsharp )
- 可以自動反序列化XML和JSON
- 支持自定義的序列化與反序列化
- 自動檢測返回的內容類型
- 支持HTTP的GET, POST, PUT, HEAD, OPTIONS, DELETE等操作
- 可以上傳多文件
- 支持oAuth 1, oAuth 2, Basic, NTLM and Parameter-based Authenticators等授權驗證等
- 支持異步操作
- 極易上手並應用到任何項目中
以上是RestSharp的主要特點,通用它你可以很容易地用程序來處理一系列的網絡請求(GET, POST, PUT, HEAD, OPTIONS, DELETE),並得到返回結果。 最后是官方的應用示例,就是如下這么簡單:
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}", Method.POST);
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
var postdata = new
{
username = "yanyangtian",
password = "123456",
nickname = "艷陽天"
};
var json = request.JsonSerializer.Serialize(postdata);
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
// execute the request
RestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;
// easy async support
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
Console.WriteLine(response.Data.Name);
});
// abort the request on demand
asyncHandle.Abort();
