我正在从RestSharper中替换WebClient来调用Rest客户端。 下面是WebClient的工作代码,但是相同的代码不能从RestClient
中运行Web客户端:
using (var client = new WebClient())
{
var reqparm =
new System.Collections.Specialized.NameValueCollection
{
{"client_id", _configurationTickle.ClientId},
{"client_secret", _configurationTickle.ClientSecret},
{"grant_type", "authorization_code"},
{"code", authCode},
{"redirect_uri", _configurationTickle.CallBackUrl}
};
byte[] responsebytes = client.UploadValues(url, "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
}
RestSharp:
var client1 = new RestClient(_configurationTickle.BaseUrl);
var request = new RestRequest(_configurationTickle.TokenRequestEndPoint,Method.POST);
request.AddParameter("client_id", _configurationTickle.ClientId);
request.AddParameter("client_secret", _configurationTickle.ClientSecret);
request.AddParameter("grant_type", "authorization_code");
request.AddParameter("code", authCode);
request.AddParameter("redirect_uri", _configurationTickle.CallBackUrl);
IRestResponse response = client1.Execute(request);
请你帮忙解决RestSharp中的请求错误,我收到了无效的请求错误。 提前谢谢。
答案 0 :(得分:0)
urlencoded
类型请求应如下所示,请查看以下修改后的代码
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "Key1=value1&Key2=value2&....", ParameterType.RequestBody);
修改后的代码:
var client1 = new RestClient(_configurationTickle.BaseUrl);
var request = new RestRequest(_configurationTickle.TokenRequestEndPoint,Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
String body="client_id="+_configurationTickle.ClientId+"&client_secret="+_configurationTickle.ClientSecret+"&grant_type=authorization_code&code="+authCode+"&redirect_uri="_configurationTickle.CallBackUrl;
request.AddParameter("application/x-www-form-urlencoded", body, ParameterType.RequestBody);