RestSharp 一个.NET(C#)的HTTP辅助类组件

互联网上关于.NET(C#)的HTTP相关的辅助类还是比较多的,这里再为大家推荐一个.NET的HTTP辅助类,它叫RestSharp。RestSharp是一个轻量的,不依赖任何第三方的组件或者类库的Http的组件。RestSharp具有以下的优点:

  1. 支持.NET 3.5+,Silverlight 4, Windows Phone 7, Mono, MonoTouch, Mono for Android, Compact Framework 3.5等
  2. 通过NuGet方便引入到任何项目 ( Install-Package restsharp )
  3. 可以自动反序列化XML和JSON
  4. 支持自定义的序列化与反序列化
  5. 自动检测返回的内容类型
  6. 支持HTTP的GET, POST, PUT, HEAD, OPTIONS, DELETE等操作
  7. 可以上传多文件
  8. 支持oAuth 1, oAuth 2, Basic, NTLM and Parameter-based Authenticators等授权验证等
  9. 支持异步操作
  10. 极易上手并应用到任何项目中

以上是RestSharp的主要特点,通用它你可以很容易地用程序来处理一系列的网络请求(GET, POST, PUT, HEAD, OPTIONS, DELETE),并得到返回结果。 最后是官方的应用示例,就是如下这么简单:

var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);

var request = new RestRequest("resource/{id}", Method.POST);
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);

var postdata = new
            {
                username = "yanyangtian",
                password = "123456",
                nickname = "艳阳天"
            };
var json = request.JsonSerializer.Serialize(postdata);
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);

// execute the request
RestResponse 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();

 

posted @ 2017-06-28 15:40  理论家  阅读(16186)  评论(1编辑  收藏  举报
点击这里给我发消息