使用Restsharp实现http请求

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

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

restsharp 官网 : http://restsharp.org

 

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

 

贴一下官方的例子:

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 response2 = client.Execute(request);
var name = response2.Data.Name;

// easy async support
client.ExecuteAsync(request, response => {
    Console.WriteLine(response.Content);
});

// async with deserialization
var asyncHandle = client.ExecuteAsync(request, response => {
    Console.WriteLine(response.Data.Name);
});

// abort the request on demand
asyncHandle.Abort();

  我去撸代码了,也许会有补充……

转载于:https://www.cnblogs.com/simon-lu/p/9042252.html

你可能感兴趣的:(使用Restsharp实现http请求)