示例:
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;
// easy async support
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
Console.WriteLine(response.Data.Name);
});
// abort the request on demand
asyncHandle.Abort();
1.使用
(1)通过github下载 : https://github.com/restsharp/RestSharp
( 2 )通过NuGet把RestSharp引入项目中
通过RestSharp的相关接口,快速调用RESTful API
以调用DaoCloud的API为例
1 2 3 4 5 6 7 8 9 10 11 12 |
// <add key="DaoCloudAPI_BASE_URL" value="https://openapi.daocloud.io/"/> // <add key="DaoCloudAPI_GETAPP_URL" value="v1/apps"/> string getAppUrl = ConfigurationManager.AppSettings["DaoCloudAPI_GETAPP_URL"]; //构建客户端对象 RestClient client = new RestClient(Base_url); //构建请求,getAppUrl请求地址 RestRequest request = new RestRequest(getAppUrl, Method.GET); //设置请求头部参数 request.AddHeader("Authorization", API_Token); //获取返回值 var _result = client.Execute(request); |
以上代码运行结果:
以上是使用同步方式调用,由于网络通信的不稳定性,建议使用异步方式进行调用:
1 2 3 4 |
client.ExecuteAsync(request,response => { Console.WriteLine(response.Content); }); |
对于RESTful的返回值json数据,在RestSharp中已经有相关的反序列化实现,当然首先得有json对应的C#实体类,通过在线的一些网站可以很快获得这个类:
http://www.jsons.cn/jsontomodel/
通过以上网站,转换得到C#实体类代码:
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 37 38 39 40 41 42 43 44 public class Package { /// <summary> /// /// </summary> public string image { get; set; } /// <summary> /// /// </summary> public string id { get; set; } } public class App_runtime { /// <summary> /// 云端测试环境 /// </summary> public string display_name { get; set; } /// <summary> /// /// </summary> public string id { get; set; } /// <summary> /// /// </summary> public string name { get; set; } } public class AppItem { /// <summary> /// /// </summary> public string enable_auto_redeploy { get; set; } ...
有了这些自动生成的JSON对应的实体类就可以使用RestSharp把返回的数据直接转换成对象了,使用如下方法即可:
1 2 3 4 5 6 7 //同步获取返回值 var _result = client.Execute<Model.DaoCloud.Root>(request); //异步获取 client.ExecuteAsync<Model.DaoCloud.Root>(request, response => { Console.WriteLine(response.Content); });
RestSharp还是十分好用的,做一个小东西刚好用到,就记下来,免得以后忘了。