首页 > 其他 > 详细

RestSharp用法小结

时间:2014-01-23 23:11:41      阅读:4510      评论:0      收藏:0      [点我收藏+]
今天有空,小结一下RestSharp的用法。

1. 实现接口IRestAPIExecutor

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

  • 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);
        }
    }
}

RestSharp用法小结

原文:http://www.cnblogs.com/Mainz/p/3531243.html

(1)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!