推薦一個.NET(C#)的HTTP輔助類組件--restsharp


互聯網上關於.NET(C#)的HTTP相關的輔助類還是比較多的,這里再為大家推薦一個.NET的HTTP輔助類,它叫RestSharp。RestSharp是一個輕量的,不依賴任何第三方的組件或者類庫的Http的組件。RestSharp具有以下的優點:

  1. 支持.NET 3.5+,Silverlight 4, Windows Phone 7, Mono, MonoTouch, Mono for Android, Compact Framework 3.5等
  2. 通過NuGet方便引入到任何項目
  3. 可以自動反序列化XML和JSON
  4. 支持自定義的序列化與反序列化
  5. 自動檢測返回的內容類型
  6. 支持HTTP的GET, POST, PUT, HEAD, OPTIONS, DELETE等操作
  7. 可以上傳多文件
  8. 支持oAuth 1, oAuth 2, Basic, NTLM and Parameter-based Authenticators等授權驗證等
  9. 支持異步操作
  10. 極易上手並應用到任何項目中

以上是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.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
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);

// 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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM