上篇文章《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