C# RestSharp应用
开通博客是想将自己所学的东西记录下来,以便自己查缺补漏,希望自己能坚持下去
正题关于RestSharp的使用
下载
NuGet直接搜索即可,最新版本RestSharp需要.net framework 4.5.2及以上支持
Json序列化工具:Newtonsoft.Json,直接由NuGet下载
官网说明:
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}");
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// add parameters for all properties on an object
request.AddJsonObject(@object);
// or just whitelisted properties
request.AddObject(object, "PersonId", "Name", ...);
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile("file", path);
// execute the request
var response = client.Post(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();
var response2 = client.Post(request);
var name = response2.Data.Name;
// or download and save file to disk
client.DownloadData(request).SaveAs(path);
// easy async support
await client.ExecuteAsync(request);
// async with deserialization
var asyncHandle = client.PostAsync(request, response => {
Console.WriteLine(response.Data.Name);
});
// abort the request on demand
asyncHandle.Abort();
写一个工具类
public class RestSharpApiUtil
{
#region 暴露执行方法
///
/// 组装Client,Request,并执行Http请求
///
/// 返回值类型
/// 基地址
/// 相对地址
/// 请求类型
/// Get/Put/Delete/Post等参数
/// post请求体
///
public static ResponseMessage RestAction(string baseUrl, string relativeUrl, Method method=Method.GET,List lstParam=null)
{
var client = new RestClient(baseUrl);
return RestMethod(client, InstallRequest(relativeUrl,method,lstParam));
}
///
/// 异步请求无返回值
///
///
///
///
///
///
public static void RestActionNoResponseAsync(string baseUrl, string relativeUrl, Method method = Method.GET, List lstParam = null)
{
var client = new RestClient(baseUrl);
RestMethodWithOutReturnAsync(client, InstallRequest(relativeUrl, method, lstParam));
}
#endregion
#region 底层调用,并不暴露方法
///
/// Http请求
///
///
///
///
///
static ResponseMessage RestMethod(RestClient client, RestRequest request)
{
RestResponse restResponse = (RestResponse)client.Execute(request);
try
{
return restResponse == null ? new ResponseMessage() :
string.IsNullOrWhiteSpace(restResponse.Content) ? new ResponseMessage() :
JsonConvert.DeserializeObject>(restResponse.Content);
}
catch (Exception ex)
{
return new ResponseMessage() { success = false };
}
}
///
/// 无返回值异步调用
///
///
///
static void RestMethodWithOutReturnAsync(RestClient client, RestRequest request)
{
RestResponse restResponse;
var asyncHandle = client.ExecuteAsync(request, response =>
{
restResponse = (RestResponse)response;
});
asyncHandle.Abort();
}
///
/// 组装Request
///
///
///
///
///
static RestRequest InstallRequest(string relativeUrl, Method method = Method.GET, List lstParam = null)
{
var request = new RestRequest(relativeUrl, method);
if (lstParam != null)
{
foreach (RestParam p in lstParam)
{
switch (p.ParamType)
{
case EmParType.UrlSegment:
request.AddUrlSegment(p.Key, p.Value);
break;
case EmParType.Param:
request.AddParameter(p.Key, p.Value);
break;
case EmParType.Body:
request.AddJsonBody(p.Value);
break;
default:
break;
}
}
}
return request;
}
#endregion
}
其中用到两个类:ResponseMessage:返回值实体,根据自己的业务组装即可
RestParam:参数实体以及参数类型
转自:https://blog.csdn.net/dengzitui/article/details/88715385