上篇文章《C# 服務端篇之實現RestFul Service開發(簡單實用)》講解到,如果開發一個簡單的Restful風格的Service,也提到了簡單創建一個Restful Client去如何調用Service的API,本文只要再次詳細講解一個高效便捷易擴展的Restful Client幫助類,就是RestSharp,如果只是想自己簡單實現一個Restful Client的方法,可以參考筆者上篇文章講解的Restful Service提到的測試Client的Demo,好了,下面主要講解一下今天的主(豬)角(腳)—RestSharp。
一、RestSharp簡紹
RestSharp是一個輕量的,不依賴任何第三方的組件或者類庫的Http的組件。RestSharp具體以下特性;
1、支持.NET 3.5+,Silverlight 4, Windows Phone 7, Mono, MonoTouch, Mono for Android, Compact Framework 3.5等
2、通過NuGet方便引入到任何項目 ( Install-Package restsharp )
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),並得到返回結果
GitHub地址--->傳送門,下載源碼,根據不同的平台架構,編譯出對應的dll文件。如圖所示:
下面是官方的應用示例,使用起來簡單快捷:
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();
二、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 //方法二、使用第三方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服務端,編譯運行,結果如下:
至此、RestSharp的簡單應用就介紹這里了,后期將進一步介紹基於RestSharp的完善和二次擴展
PS:如有疑問,請留言,未經允許,不得私自轉載,轉載請注明出處:https://www.cnblogs.com/xuliangxing/p/8746277.html