現在互聯網上的服務接口都是Restful的,SOAP的Service已經不是主流。.NET/Mono下如何消費Restful Service呢,再也沒有了方便的Visual Studio的方便生產代理的工具了,你還在用HttpWebRequest 自己封裝嗎?Restful Service還有授權問題,自己寫出來的代碼是不是很不優雅?通常Restful Service返回的數據格式是XML或者Json,還要設置服務的輸入參數等等,使用起來很復雜。本文向你推薦一個開源的庫RestSharp輕松消費Restful Service。RestSharp是一個開源的.NET平台下REST和Http API的客戶端庫,支持的平台有.NET 3.5/4、Mono、Mono for Android、MonoTouch、Windows Phone 7.1 Mango。他可以簡化我們訪問Restful服務,可以到這里下載代碼 https://github.com/johnsheehan/RestSharp/archives/master 更簡單的使用NuGet。RestSharp使用Json.Net處理 Json數據同Poco對象的序列化。
下面分別從庫的使用方式上進行介紹,使用的Restful Service是騰訊社區開放平台(http://opensns.qq.com/)。
1、服務認證,RestSharp定義了一個認證授權的接口 IAuthenticator ,有NtlmAuthenticator、HttpBasicAuthenticator、OAuth1Authenticator、OAuth2Authenticator幾種,基本上可以滿足要求了,騰訊社區開放平台使用OAuth2,騰訊社區開放平台額外增加了一個OpenId的參數,我們從OAuth2Authenticator的基類繼承實現一個:
public class OAuthUriQueryParameterAuthenticator : OAuth2Authenticator
{
private readonly string openId;
private readonly string consumerKey;
public OAuthUriQueryParameterAuthenticator(string openId, string accessToken, string consumerkey)
:base(accessToken)
{
this.openId = openId;
this.consumerKey = consumerkey;
}
public override void Authenticate(IRestClient client, IRestRequest request)
{
request.AddParameter("access_token", AccessToken, ParameterType.GetOrPost);
request.AddParameter("openid", openId, ParameterType.GetOrPost);
request.AddParameter("oauth_consumer_key", consumerKey, ParameterType.GetOrPost);
}
2、Get請求方法,下面的例子是根據access_token獲得對應用戶身份的openid: https://graph.qq.com/oauth2.0/me?access_token=YOUR_ACCESS_TOKEN
public string GetOpenId(string accessToken)
{
RestClient _restClient = new RestClient(Endpoints.ApiBaseUrl);
var request = _requestHelper.CreateOpenIDRequest(accessToken);
var response = Execute(request);
var openid = GetUserOpenId(response.Content);
return openid;
}
private RestSharp.RestResponse Execute(RestRequest request)
{
//返回的結果
var response = _restClient.Execute(request);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new QzoneException(response);
}
return response;
}
internal RestRequest CreateOpenIDRequest(string accesstoken)
{
var request = new RestRequest(Method.GET);
request.Resource = "oauth2.0/me?access_token={accesstoken}";
request.AddParameter("accesstoken", accesstoken, ParameterType.UrlSegment);
return request;
}
上面代碼里涉及到了服務的輸入參數通過AddParameter方法很方便的處理,是不是很簡單。
3、POST請求服務,下面的例子是發表一條微博信息(純文本)到騰訊微博平台上http://wiki.opensns.qq.com/wiki/%E3%80%90QQ%E7%99%BB%E5%BD%95%E3%80%91add_t:
/// <summary>
/// 發表一條微博信息(純文本)到騰訊微博平台上
/// </summary>
/// <param name="content">表示要發表的微博內容。必須為UTF-8編碼,最長為140個漢字,也就是420字節。
/// 如果微博內容中有URL,后台會自動將該URL轉換為短URL,每個URL折算成11個字節。</param>
/// <param name="clientip">用戶ip,以分析用戶所在地</param>
/// <param name="jing">用戶所在地理位置的經度。為實數,最多支持10位有效數字。有效范圍:-180.0到+180.0,+表示東經,默認為0.0</param>
/// <param name="wei">用戶所在地理位置的緯度。為實數,最多支持10位有效數字。有效范圍:-90.0到+90.0,+表示北緯,默認為0.0。</param>
/// <param name="syncflag">標識是否將發布的微博同步到QQ空間(0:同步; 1:不同步;),默認為0.</param>
/// <returns></returns>
internal AddWeiboResult AddWeibo(string content, string clientip = "", string jing = "", string wei = "", int syncflag = 0)
{
RestClient _restClient = new RestClient(Endpoints.ApiBaseUrl);
_restClient.Authenticator = new OAuthUriQueryParameterAuthenticator(context.AccessToken.OpenId, context.AccessToken.AccessToken, context.Config.GetAppKey());
var request = _requestHelper.CreateAddWeiboRequest(content, clientip,jing,wei,syncflag);
var response = Execute(request);
var payload = Deserialize<AddWeiboResult>(response.Content);
return payload;
}
internal RestRequest CreateAddWeiboRequest(string content, string clientip, string jing, string wei, int syncflag)
{
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.Resource = "t/add_t";
request.AddParameter("content", content);
if (!string.IsNullOrEmpty(clientip))
{
request.AddParameter("clientip", clientip);
}
if (!string.IsNullOrEmpty(jing))
{
request.AddParameter("jing", jing);
}
if (!string.IsNullOrEmpty(wei))
{
request.AddParameter("wei", wei);
}
request.AddParameter("syncflag", syncflag);
return request;
}
這個方法需要使用到OAuth2的認證和前面的不需要認證的接口比較起來並沒有變復雜,代碼很優雅。
4、來點復雜的,發個圖片微博,RestSharp對HttpFile的封裝也很不錯,使用起來一樣很簡單,看代碼中的紅色部分:
internal RestRequest CreateAddPictureWeiboRequest(string content, string clientip, string jing, string wei, int syncflag, string fileName, byte[] bytes)
{
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
var boundary = string.Concat("--", Util.GenerateRndNonce());
request.AddHeader("Content-Type", string.Concat("multipart/form-data; boundary=", boundary));
request.Resource = "t/add_pic_t";
request.AddParameter("content", content);
if (!string.IsNullOrEmpty(clientip))
{
request.AddParameter("clientip", clientip);
}
if (!string.IsNullOrEmpty(jing))
{
request.AddParameter("jing", jing);
}
if (!string.IsNullOrEmpty(wei))
{
request.AddParameter("wei", wei);
}
request.AddParameter("syncflag", syncflag);
request.AddFile("pic", bytes, fileName);
return request;
}
上面這幾個API的調用已經很具有代表性了,是不是可以很好的簡化你使用Restful Service,記住DRY(don’t repeat yourself),可以很好的加速你的應用的開發。