翻译自:https://github.com/restsharp/RestSharp/wiki,转载请注明。
一、新手入门
如果只有少量一次性请求需要封装为API,则可以如下使用RestSharp :
using RestSharp; using RestSharp.Authenticators; var client = new RestClient(); client.BaseUrl = new Uri("http://twitter.com"); client.Authenticator = new HttpBasicAuthenticator("username", "password"); var request = new RestRequest(); request.Resource = "statuses/friends_timeline.xml"; IRestResponse response = client.Execute(request);IRestResponse 接口中包含了所有远程服务返回的信息,可以访问头信息(header)数据内容(content)、HTTP状态等。建议使用泛型将返回结果自动反序列化为.NET实体类。
关于错误处理:
如果发生了网络传输错误(网络瘫痪,DNS查找失败等),RestResponse.ResponseStatus 将会置为Error ,否则RestResponse.ResponseStatus的值为Completed 。如果API返回404,ResponseStatus 仍然是Completed 。如果需要访问返回的HTTP状态码,则需要查看RestResponse.StatusCode 的值,Status 属性是请求完成的标识,独立于API错误处理。
二、推荐用法
RestSharp适合作为API代理类实现的基础,下面是 Twilio类库中的一些使用示例:
创建一个包含API代理实现的类,声明一个执行方法当作所有请求的入口。这个执行方法允许设置常用参数和其它跨请求共享设置(例如认证),因为每一个请求都需要帐户ID和密钥,所以在建立新的代理实例时都需要传递这两个值。需要注意的是执行过程中不会抛出异常,但是可以在ErrorException 中访问到异常信息。
// TwilioApi.cs public class TwilioApi { const string BaseUrl = "https://api.twilio.com/2008-08-01"; readonly string _accountSid; readonly string _secretKey; public TwilioApi(string accountSid, string secretKey) { _accountSid = accountSid; _secretKey = secretKey; } public T Execute<T>(RestRequest request) where T : new() { var client = new RestClient(); client.BaseUrl = new System.Uri(BaseUrl); client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey); request.AddParameter("AccountSid", _accountSid, ParameterType.UrlSegment); // used on every request var response = client.Execute<T>(request); if (response.ErrorException != null) { const string message = "Error retrieving response. Check inner details for more info."; var twilioException = new ApplicationException(message, response.ErrorException); throw twilioException; } return response.Data; } }接下来,定义一个实体类来映射API返回的数据,再定义一个方法用来访问API同时获取返回的Call资源的具体信息:
// Call.cs public class Call { public string Sid { get; set; } public DateTime DateCreated { get; set; } public DateTime DateUpdated { get; set; } public string CallSegmentSid { get; set; } public string AccountSid { get; set; } public string Called {
