使用Restsharp实现http请求 - Simon.lu - 博客园

来源: 使用Restsharp实现http请求 – Simon.lu – 博客园

之前使用Postman 的时候 发现 自动生成的code 里面 的C# 代码是 使用的 Restsharp。

今天用要做http 请求,去调用其他接口,就决定使用 Restsharp 实现。

restsharp 官网 : http://restsharp.org

 

首先 在nuget 安装依赖包, Install-Package RestSharp -Version 106.2.2

 

贴一下官方的例子:

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
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) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏