官方文档:https://restsharp.dev/intro.html#introduction
c# RestSharp(http请求):https://blog.csdn.net/czjnoe/article/details/106482422
包引入
- RestSharp
- RestSharp.Serializers.NewtonsoftJson
如无必要不要使用AddJsonBody,因为某些接口会不识别
POST请求
参数为JSON
//定义
private RestClient client { get; set; }
//帮助类方法
public MoneyCardHelper()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
| SecurityProtocolType.Tls
| SecurityProtocolType.Tls11
| SecurityProtocolType.Tls12;
client= new RestClient(baseApi);//定义根路径
client.UseNewtonsoftJson();//使用NewtonsoftJson序列化,需要引入NewtonsoftJson包
client.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
}
//方法中代码
string url = "Test/GetProjectList";
var request = new RestRequest(url, DataFormat.Json);
//添加POST参数
request.AddOrUpdateParameter("client_id", client_id);
request.AddOrUpdateParameter("client_secret", client_secret);
request.AddOrUpdateParameter("grant_type", grant_type);
var response = client.Post<GetProjectListDto>(request);
if (response.IsSuccessful){
//请求成功
var data = response.Data;//返回的结果
}else{
response.ErrorMessage;//错误信息
}
获取结果if (response.IsSuccessful)时候后,response.Data就是设定的返回类型数据
Get请求
string url = "/test/all_info";
var request = new RestRequest(url, DataFormat.Json);
request.AddQueryParameter("statusCode", "0");
var response = client.Get<SyncInformationDto>(request);
if (response.IsSuccessful)
{
//请求成功
var data = response.Data;//返回的结果
}
token验证
//access_token为token文本,token_type为类型,例如:“Bearer”
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(
access_token, token_type
);
标签:HTTP,请求,request,token,client,var,RestSharp,response
From: https://www.cnblogs.com/itljf/p/17400492.html