1.RestSharp的介绍
RestSharp是一个轻量级的,不依赖任何第三方的组件或者类库的Http的组件
优势:
- 通过NuGet方便引入到任何项目(注意要与framework框架匹配,我匹配的是framework4.8ok,4.0失败了)
- 可以自动反序列化XML和JSON
- 支持自定义的序列化与反序列化
- 自动检测返回的内容类型
- 支持HTTP的GET, POST, PUT, HEAD, OPTIONS, DELETE等操作
- 可以上传多文件
- 支持异步操作
- 极易上手并应用到任何项目中
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
该类在请求第三方平台时使用到了,另外一篇中有写平台群发短信功能。
来源:CSDN
作者:chunchunlaila
链接:https://blog.csdn.net/chunchunlaila/article/details/104482005