RestSharp:C#的http辅助类

柔情痞子 提交于 2020-02-24 23:47:09

1.RestSharp的介绍

RestSharp是一个轻量级的,不依赖任何第三方的组件或者类库的Http的组件

优势:

  1. 通过NuGet方便引入到任何项目(注意要与framework框架匹配,我匹配的是framework4.8ok,4.0失败了
  2. 可以自动反序列化XML和JSON
  3. 支持自定义的序列化与反序列化
  4. 自动检测返回的内容类型
  5. 支持HTTP的GET, POST, PUT, HEAD, OPTIONS, DELETE等操作
  6. 可以上传多文件
  7. 支持异步操作
  8. 极易上手并应用到任何项目中

2.官方应用示例

//构建客户端对象
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);

 //构建post请求
var request = new RestRequest("resource/{id}", Method.POST);
request.AddUrlSegment("id", "123"); // 替换请求中的标记
 
// 设置请求头部删除
request.AddHeader("header", "value");
 
// add files to upload (works with compatible verbs)
request.AddFile(path);
 
var postdata = new
            {
                username = "dangxiaochun",
                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();

参考资料:https://www.seoxiehui.cn/article-121214-1.html

HTTP协议header标头详解

该类在请求第三方平台时使用到了,另外一篇中有写平台群发短信功能。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!