RestSharp:C#的http辅助类

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标头详解

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

发布了30 篇原创文章 · 获赞 1 · 访问量 1158

猜你喜欢

转载自blog.csdn.net/chunchunlaila/article/details/104482005