今天有空,小结一下RestSharp的用法。

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

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

比如下面的实体类:

Public class Employee {
Public string EmployeeId {get; set ;}
Public int EmployeeName {get; set ;}
Public int EmployeeAge {get ; set ;}
}

对应的XML:

<Employee>
< EmployeeId >1< /EmployeeId >
< EmployeeName>John</ EmployeeName>
< EmployeeAge>30</ EmployeeAge>
<Employee>

对应的JSON:

{
EmployeeId:1
EmployeeName:”John”
EmployeeAge:30
}

1. 异步调用

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

2. 实现接口IRestAPIExecutor

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码
using System.Xml.Linq;
using RestSharp;
using System;
using System.Configuration;
using System.IO;
using System.Linq; namespace myCompany
{
public class myClient
{
#region Initialization private readonly IRestAPIExecutor restAPIExecutor; public myClient()
{
restAPIExecutor = new RestAPIExecutor(ConfigurationManager.AppSettings[Utility.Constants.Configuration.CmsBaseUri],
DateParameterFormat: ConfigurationManager.AppSettings[Utility.Constants.Configuration.DateFormat]);
} public myClient(string CmsBaseURI, string dateFormat, string username = null, string password = null)
{
restAPIExecutor = !string.IsNullOrEmpty(username) ? new RestAPIExecutor(CmsBaseURI, DateParameterFormat: dateFormat, Authenticator: new HttpBasicAuthenticator(username, password)) : new RestAPIExecutor(CmsBaseURI, DateParameterFormat: dateFormat);
} #endregion //HTTP GET,返回JSON,自动反序列化为实体类
public OrderResult GetOrders(DateTime date, string channel = null, string merchant = null, string venue = null)
{
var request = new RestRequest(ConfigurationManager.AppSettings[Utility.Constants.Configuration.API_Campaign_List], Method.GET);
request.AddParameter("date", string.Format("{0:yyyy-MM-dd}", date));
if (!string.IsNullOrEmpty(channel)) request.AddParameter("channel", channel);
if (!string.IsNullOrEmpty(merchant)) request.AddParameter("merchant", merchant);
if (!string.IsNullOrEmpty(venue)) request.AddParameter("venue", venue); return restAPIExecutor.GenericExecute<OrderResult>(request);
} //HTTP GET,获得返回的XML字符串,并转为XDocument
public XDocument GetOrderDetailsXml(int OrderID)
{
var request = new RestRequest(ConfigurationManager.AppSettings[Utility.Constants.Configuration.API_Order_Details], Method.GET);
request.AddHeader(Application.AcceptHttpHeader, Application.AcceptHttpHeaderValue);
request.AddParameter("OrderID", OrderID.ToString(), ParameterType.UrlSegment);
var response = restAPIExecutor.Execute(request); //获得返回的http header里面的字段
//var sha = response.Headers.Where(s => s.Name == Application.SHAHttpHeader).Select(s => s.Value).FirstOrDefault(); return XDocument.Parse(response.Content);
} //HTTP POST, 提交一个zip包
public IRestResponse UploadZipFile(string fileName, byte[] fileContent)
{
var request = new RestRequest(ConfigurationManager.AppSettings[Utility.Constants.Configuration.API_POP_ZIP_Upload], Method.POST);
request.AddHeader("Content-Type", "application/zip");
request.AddParameter("filename", fileName);
request.AddFile("gzip", fileContent, fileName, "application/zip"); return restAPIExecutor.Execute(request);
} //HTTP GET, Partial download, 分段下载大的内容,可能包含很多个请求。最后还需要另外发一个请求获得整个文件的SHA码
public byte[] DownloadPartialOrderMedia()
{
var request = new RestRequest(ConfigurationManager.AppSettings[Utility.Constants.Configuration.API_POP_ZIP_Upload], Method.POST);
request.AddParameter("filename", fileName);
return restAPIExecutor.DownloadData(request);
} }
}

3. 异步读取RESTful API

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

扩展方法:

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用法小结的更多相关文章

  1. 转载:Hadoop排序工具用法小结

    本文转载自Silhouette的文章,原文地址:http://www.dreamingfish123.info/?p=1102 Hadoop排序工具用法小结 发表于 2014 年 8 月 25 日 由 ...

  2. [No000010]Ruby 中一些百分号(%)的用法小结

    #Ruby 中一些百分号(%)的用法小结 #这篇文章主要介绍了Ruby 中一些百分号(%)的用法小结,需要的朋友可以参考下 what_frank_said = "Hello!"#% ...

  3. C++ typedef用法小结 (※不能不看※)

    C++ typedef用法小结 (※不能不看※) 第一.四个用途 用途一: 定义一种类型的别名,而不只是简单的宏替换.可以用作同时声明指针型的多个对象.比如:char* pa, pb; // 这多数不 ...

  4. 函数fgets和fputs、fread和fwrite、fscanf和fprintf用法小结 (转)

    函数fgets和fputs.fread和fwrite.fscanf和fprintf用法小结 字符串读写函数fgets和fputs 一.读字符串函数fgets函数的功能是从指定的文件中读一个字符串到字符 ...

  5. 1:CSS中一些@规则的用法小结 2: @media用法详解

    第一篇文章:@用法小结 第二篇文章:@media用法 第一篇文章:@用法小结 这篇文章主要介绍了CSS中一些@规则的用法小结,是CSS入门学习中的基础知识,需要的朋友可以参考下     at-rule ...

  6. 英语语法最终珍藏版笔记- 21it 用法小结

    it 用法小结 it 在英语中的意思较多,用法较广,现总结如下. 一.it作句子的真正主语 1.it 指前面已经提到过的人或事物,有时指心目中的或成为问题的人或事物,作真正主语. 例如: What’s ...

  7. [转]ssh常用用法小结

    ssh常用用法小结 1.连接到远程主机: 命令格式 : ssh name@remoteserver 或者 ssh remoteserver -l name 说明:以上两种方式都可以远程登录到远程主机, ...

  8. 结构体定义 typedef struct 用法详解和用法小结

    typedef是类型定义的意思.typedef struct 是为了使用这个结构体方便.具体区别在于:若struct node {}这样来定义结构体的话.在申请node 的变量时,需要这样写,stru ...

  9. typedef用法小结

    typedef用法小结- - 注意:本文转自网络,版权归原作者所有. typedef typedef用法小结- - 这两天在看程序的时候,发现很多地方都用到typedef,在结构体定义,还有一些数组等 ...

随机推荐

  1. python chm 中文帮助 (2.7 和 3.4)

    sphinx-build 生成的(htmlhelp) 存在2个问题 1.生成的html 编码 cp2152,需要修改/sphinx/builders/html.py ctx['encoding'] = ...

  2. Java for LeetCode 172 Factorial Trailing Zeroes

    Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in log ...

  3. CodeForces - 407A

    Triangle Time Limit: 1000MS   Memory Limit: 262144KB   64bit IO Format: %I64d & %I64u Submit Sta ...

  4. CSS备忘

    垂直居中:           先height再ling-height,都设成一样高 span 垂直居中:vertical-align:50%设置外边距:           margin-top,m ...

  5. 取余运算(codevs 1497)

    题目描述 Description 输入b,p,k的值,编程计算bp mod k的值.其中的b,p,k*k为长整型数(2^31范围内). 输入描述 Input Description b p k 输出描 ...

  6. markdown下编辑latex数学公式

    在利用为知笔记编写笔记的时候,有时需要用的markdown,只要把文件名加上后缀.md,就可以使用markdown语法,以下介绍在markdown下编辑latex数学公式. 使用LaTeX写公式的基本 ...

  7. Nginx 服务器安装及配置文件详解

    原文出处: Sean Chow(@SeanLoook)   欢迎分享原创到伯乐头条 Nginx 在工作中已经有好几个环境在使用了,每次都是重新去网上找博客,各种编译配置,今天自己也整理一份安装文档和 ...

  8. Java Hour 48 Servlet 简介

    搞Java Web 开发,绕不开的就是Servlet 了.传说Servlet 是一种比JSP 更加古董的动态网页编程技术.在没有JSP 之前,Servlet 同时充当了展现层,业务逻辑层和持久层. 这 ...

  9. android wheelview 滚轮控件

    项目地址:http://android-wheel.googlecode.com/svn

  10. Scala中的Apply

    文章来自:http://www.cnblogs.com/hark0623/p/4194940.html  转载请注明 /** * Created by Administrator on 2014-12 ...