[关闭]
@KingMe 2016-01-13T12:21:03.000000Z 字数 1745 阅读 1838

.Net 使用 webapi 接口

webapi post body .net


首先安利一下 PostMan 这个工具,他能在测试接口的同时,生成多种语言对应的代码

1. RestSharp

官网代码

.net的WebRequest对需要发送body数据的情况好像支持不佳
所以选择了 RestSharp这个库,使用非常简洁。

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
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();

2. POST 包含body参数

var client = new RestClient("http://X.X.X.X/login");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("postman-token", "X-X-X-X-X");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("kss-accessid", "X");
request.AddHeader("kss-sig-exptime", "X");
request.AddHeader("kss-sig", "X");
request.AddParameter("application/x-www-form-urlencoded", "username=X&password=X&client=X", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
string content = response.Content;
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注