RestSharp用法小结
今天有空,小结一下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用法小结的更多相关文章
- 转载:Hadoop排序工具用法小结
本文转载自Silhouette的文章,原文地址:http://www.dreamingfish123.info/?p=1102 Hadoop排序工具用法小结 发表于 2014 年 8 月 25 日 由 ...
- [No000010]Ruby 中一些百分号(%)的用法小结
#Ruby 中一些百分号(%)的用法小结 #这篇文章主要介绍了Ruby 中一些百分号(%)的用法小结,需要的朋友可以参考下 what_frank_said = "Hello!"#% ...
- C++ typedef用法小结 (※不能不看※)
C++ typedef用法小结 (※不能不看※) 第一.四个用途 用途一: 定义一种类型的别名,而不只是简单的宏替换.可以用作同时声明指针型的多个对象.比如:char* pa, pb; // 这多数不 ...
- 函数fgets和fputs、fread和fwrite、fscanf和fprintf用法小结 (转)
函数fgets和fputs.fread和fwrite.fscanf和fprintf用法小结 字符串读写函数fgets和fputs 一.读字符串函数fgets函数的功能是从指定的文件中读一个字符串到字符 ...
- 1:CSS中一些@规则的用法小结 2: @media用法详解
第一篇文章:@用法小结 第二篇文章:@media用法 第一篇文章:@用法小结 这篇文章主要介绍了CSS中一些@规则的用法小结,是CSS入门学习中的基础知识,需要的朋友可以参考下 at-rule ...
- 英语语法最终珍藏版笔记- 21it 用法小结
it 用法小结 it 在英语中的意思较多,用法较广,现总结如下. 一.it作句子的真正主语 1.it 指前面已经提到过的人或事物,有时指心目中的或成为问题的人或事物,作真正主语. 例如: What’s ...
- [转]ssh常用用法小结
ssh常用用法小结 1.连接到远程主机: 命令格式 : ssh name@remoteserver 或者 ssh remoteserver -l name 说明:以上两种方式都可以远程登录到远程主机, ...
- 结构体定义 typedef struct 用法详解和用法小结
typedef是类型定义的意思.typedef struct 是为了使用这个结构体方便.具体区别在于:若struct node {}这样来定义结构体的话.在申请node 的变量时,需要这样写,stru ...
- typedef用法小结
typedef用法小结- - 注意:本文转自网络,版权归原作者所有. typedef typedef用法小结- - 这两天在看程序的时候,发现很多地方都用到typedef,在结构体定义,还有一些数组等 ...
随机推荐
- PHP+七牛云存储上传图片代码片段
2014年11月14日 16:37:51 第一段代码是上传单个图片的,第二个是上传多个图片的 //上传到七牛 //单个文件 //formname: 表单名字; pre: 图片Url中显示的图片名字(也 ...
- Java for LeetCode 066 Plus One
Given a non-negative number represented as an array of digits, plus one to the number. The digits ar ...
- 取余运算(codevs 1497)
题目描述 Description 输入b,p,k的值,编程计算bp mod k的值.其中的b,p,k*k为长整型数(2^31范围内). 输入描述 Input Description b p k 输出描 ...
- C++ 提取字符串中的数字
C++ 提取字符串中的数字 #include <iostream> using namespace std; int main() { ] = "1ab2cd3ef45g&quo ...
- WMI
https://wiki.jenkins-ci.org/display/JENKINS/Windows+slaves+fail+to+start+via+DCOM#Windowsslavesfailt ...
- php设置和获取cookie
php设置和获取cookie setcookie()调用只带有name参数的setcookie(); ()使失效时间为time()或time-; <?php setcookie(); PHP提供 ...
- Rational Software Architect V8.5.1安装
转自:http://blog.sina.com.cn/s/blog_4a0238270101bupg.html IBM Rational Software Architect (RSA) 是 IBM ...
- android 获取路径目录方法以及判断目录是否存在,创建目录
Environment 常用方法: * 方法:getDataDirectory()解释:返回 File ,获取 Android 数据目录.* 方法:getDownloadCacheDirectory( ...
- diff和common
diff 命令 diff命令:找出两个文件的不同点,用于比较文件的差异 linux上非常重要的工具,一般用于制作补丁文件,特别是比较两个版本不同的文件以找到改动的地方. diff在命令行中打印每一个行 ...
- asp.net控件开发基础(1)(转)原文更多内容
asp.net本身提供了很多控件,提供给我们这些比较懒惰的人使用,我认为控件的作用就在此,因为我们不想重复工作,所以要创建它,这个本身便是一个需求的关系,所以学习控件开发很有意思. wrox网站上有本 ...