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测试

 

相关文章
相关标签/搜索