当前位置: 首页 > 工具软件 > RestSharp > 使用案例 >

RestSharp用法小结

池赞
2023-12-01

今天有空,小结一下RestSharp的用法。可能通过 nuget 进行安装。

RestSharp内置了XML和JSON的反序列化(deserializers )。

  • application/json – JsonDeserializer
  • application/xml – XmlDeserializer
  • text/json – JsonDeserializer
  • text/xml – XmlDeserializer
  • * – XmlDeserializer (all other content types not specified)

比如下面的实体类:

1
2
3
4
5
Public class  Employee {
     Public string  EmployeeId { get ; set  ;}
     Public int  EmployeeName { get ; set  ;}
     Public int  EmployeeAge { get  ; set   ;}
}

对应的XML:

1
2
3
4
5
< Employee >
        < EmployeeId  >1< / EmployeeId  >
        < EmployeeName >John</ EmployeeName >
        < EmployeeAge >30</ EmployeeAge >
< Employee >

对应的JSON:

1
2
3
4
5
{
   EmployeeId:1
   EmployeeName:”John”
   EmployeeAge:30
}

1. 异步调用

1
2
3
client.ExecuteAsync(request, response => {
         Console.WriteLine(response.Content);
    });

2. 实现接口IRestAPIExecutor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using  RestSharp;
using  System;
using  System.Threading.Tasks;
 
namespace  myCompany
{
     public  class  RestAPIExecutor : IRestAPIExecutor
     {
         public  string  BaseUrl { get ; set ; }
 
         public  string  DefaultDateParameterFormat { get ; set ; }
 
         public  IAuthenticator DefaultAuthenticator { get ; set ; }
 
         private  RestClient client;
 
         public  RestAPIExecutor( string  CmsBaseURI, IAuthenticator Authenticator = null , string  DateParameterFormat = null )
         {
             BaseUrl = CmsBaseURI;
             DefaultAuthenticator = Authenticator;
             
             client = new  RestClient();
 
             if  (DefaultAuthenticator != null )
                 client.Authenticator = DefaultAuthenticator;
 
             if  (DateParameterFormat != null )
                 DefaultDateParameterFormat = DateParameterFormat;
 
             client.BaseUrl = BaseUrl;
         }
 
         public  T GenericExecute<T>(RestRequest request) where  T : new ()
         {
             request.DateFormat = string .IsNullOrEmpty(DefaultDateParameterFormat) ? "yyyy-MM-dd HH:mm:ss"  : DefaultDateParameterFormat;
 
             var  response = client.Execute<T>(request);
                         
             if  (response.ErrorException != null )
             {
                 throw  new  RestCallException( "Error retrieving response.  Check inner details for more info." , response.ErrorException);
             }
 
             return  response.Data;
         }
 
         public  RestRequestAsyncHandle AsyncGenericExecute<T>(RestRequest request, Action<IRestResponse<T>> action) where  T : new ()
         {
             request.DateFormat = string .IsNullOrEmpty(DefaultDateParameterFormat) ? "yyyy-MM-dd HH:mm:ss"  : DefaultDateParameterFormat;
             return  client.ExecuteAsync<T>(request, action);
         }
 
         public  Task<T> GetTaskAsync<T>(RestRequest request) where  T : new ()
         {           
             request.DateFormat = string .IsNullOrEmpty(DefaultDateParameterFormat) ? "yyyy-MM-dd HH:mm:ss"  : DefaultDateParameterFormat;
             return  client.GetTaskAsync<T>(request);
         }
 
         public  IRestResponse Execute(RestRequest request)
         {
             request.DateFormat = string .IsNullOrEmpty(DefaultDateParameterFormat) ? "yyyy-MM-dd HH:mm:ss"  : DefaultDateParameterFormat;
 
             var  response = client.Execute(request);
 
             if  (response.ErrorException != null )
             {
                 throw  new  RestCallException( "Error retrieving response.  Check inner details for more info." , response.ErrorException);
             }
 
             return  response;
         }
 
         public  byte [] DownloadData(RestRequest request)
         {           
             return  client.DownloadData(request);
         }
         
     }
}

3. 实现自己的业务逻辑,包括

  • HTTP GET,返回JSON,自动反序列化为实体类
  • HTTP GET,获得返回的XML字符串,并转为XDocument
  • 获得返回的http header里面的字段
  • HTTP POST, 提交一个zip包
  • HTTP GET, Partial download, 分段下载大的内容,可能包含很多个请求。最后还需要另外发一个请求获得整个文件的SHA码

3. 异步读取RESTful API

1
2
3
var  client = new  RestClient( "http://example.org" );
var  request = new  RestRequest( "product/42" , Method.GET);
var  content = await client.GetContentAsync(request);

扩展方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using  System;
using  System.Threading.Tasks;
using  RestSharp;
  
namespace  RestSharpEx
{
     public  static  class  RestClientExtensions
     {
         private  static  Task<T> SelectAsync<T>( this  RestClient client, IRestRequest request, Func<IRestResponse, T> selector)
         {
             var  tcs = new  TaskCompletionSource<T>();
             var  loginResponse = client.ExecuteAsync(request, r =>
             {
                 if  (r.ErrorException == null )
                 {
                     tcs.SetResult(selector(r));
                 }
                 else
                 {
                     tcs.SetException(r.ErrorException);
                 }
             });
             return  tcs.Task;
         }
  
         public  static  Task< string > GetContentAsync( this  RestClient client, IRestRequest request)
         {
             return  client.SelectAsync(request, r => r.Content);
         }
  
         public  static  Task<IRestResponse> GetResponseAsync( this  RestClient client, IRestRequest request)
         {
             return  client.SelectAsync(request, r => r);
         }
     }
}
 
分类:  C#
标签:  CSharp

 

 
 类似资料: