C# 客戶端篇之實現Restful Client開發(RestSharp幫助類)

  上篇文章《C# 服務端篇之實現RestFul Service開發(簡單實用)》講解到,若是開發一個簡單的Restful風格的Service,也提到了簡單建立一個Restful Client去如何調用Service的API,本文只要再次詳細講解一個高效便捷易擴展的Restful Client幫助類,就是RestSharp,若是隻是想本身簡單實現一個Restful Client的方法,能夠參考筆者上篇文章講解的Restful Service提到的測試Client的Demo,好了,下面主要講解一下今天的主(豬)角(腳)—RestSharp。html

1、RestSharp簡紹

  RestSharp是一個輕量的,不依賴任何第三方的組件或者類庫的Http的組件。RestSharp具體如下特性;json

  一、支持.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),並獲得返回結果 架構

  GitHub地址--->傳送門,下載源碼,根據不一樣的平臺架構,編譯出對應的dll文件。如圖所示:app

    

  下面是官方的應用示例,使用起來簡單快捷:框架

 1 var client = new RestClient("http://example.com");
 2 // client.Authenticator = new HttpBasicAuthenticator(username, password);
 3 
 4 var request = new RestRequest("resource/{id}", Method.POST);
 5 request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
 6 request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
 7 
 8 // add parameters for all properties on an object
 9 request.AddObject(object);
10 
11 // or just whitelisted properties
12 request.AddObject(object, "PersonId", "Name", ...);
13 
14 // easily add HTTP Headers
15 request.AddHeader("header", "value");
16 
17 // add files to upload (works with compatible verbs)
18 request.AddFile("file", path);
19 
20 // execute the request
21 IRestResponse response = client.Execute(request);
22 var content = response.Content; // raw content as string
23 
24 // or automatically deserialize result
25 // return content type is sniffed but can be explicitly set via RestClient.AddHandler();
26 IRestResponse<Person> response2 = client.Execute<Person>(request);
27 var name = response2.Data.Name;
28 
29 // or download and save file to disk
30 client.DownloadData(request).SaveAs(path);
31 
32 // easy async support
33 await client.ExecuteAsync(request);
34 
35 // async with deserialization
36 var asyncHandle = client.ExecuteAsync<Person>(request, response => {
37     Console.WriteLine(response.Data.Name);
38 });
39 
40 // abort the request on demand
41 asyncHandle.Abort();

2、RestSharp應用實例

  咱們使用上篇文章的Restful Service的Demo進行簡單測試一下,新建一個控制檯項目,引用生成好的RestSharp版本,個人是.net framework 4.5.2 框架,你們根據自身實際狀況編譯不通的版本進行引用。主要代碼以下:
異步

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using Newtonsoft.Json;
 7 using RestSharp;
 8 
 9 namespace RestFulClient
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Console.Title = "Restful客戶端第三方RestSharpDemo測試";
16             //方法2、使用第三方RestSharp
17             var client = new RestSharp.RestClient("http://127.0.0.1:7788");
18             var requestGet = new RestRequest("PersonInfoQuery/{name}", Method.GET);
19             requestGet.AddUrlSegment("name", "王二麻子");
20             IRestResponse response = client.Execute(requestGet);
21             var contentGet = response.Content;
22             Console.WriteLine("GET方式獲取結果:" + contentGet);
23 
24             var requestPost = new RestRequest("PersonInfoQuery/Info", Method.POST);
25             Info info = new Info();
26             info.ID = 1;
27             info.Name = "張三";
28             var json = JsonConvert.SerializeObject(info);
29             requestPost.AddParameter("application/json", json, ParameterType.RequestBody);
30             IRestResponse responsePost = client.Execute(requestPost);
31             var contentPost = responsePost.Content;
32             Console.WriteLine("POST方式獲取結果:" + contentPost);
33             Console.Read();
34         }
35     }
36 
37     [Serializable]
38     public class Info
39     {
40         public int ID { get; set; }
41         public string Name { get; set; }
42     }
43 }

  開啓Restful Service服務端,編譯運行,結果以下:async

  至此、RestSharp的簡單應用就介紹這裏了,後期將進一步介紹基於RestSharp的完善和二次擴展post


PS:若有疑問,請留言,未經容許,不得私自轉載,轉載請註明出處:http://www.javashuo.com/article/p-epapwasa-ko.html測試

 

相關文章
相關標籤/搜索