如何使用Restsharp与纯文本正文

时间:2017-04-06 03:45:32

标签: c# restsharp

我正在尝试实现此Ebay访问令牌WebRequest

服务器需要

  

HTTP方法:POST
  网址https://api.sandbox.ebay.com/identity/v1/oauth2/token

     

HTTP标头:

     

内容类型 = application / x-www-form-urlencoded

     

授权 =基本

     

请求正文(为便于阅读而包裹):

grant_type=client_credentials&
redirect_uri=<RuName-value>&
scope=https://api.ebay.com/oauth/api_sc

使用WebRequest如图所示

var credentials = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(clientId + ":" + clientSecret));

var request = WebRequest.Create("https://api.sandbox.ebay.com/identity/v1/oauth2/token") as HttpWebRequest;

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add(HttpRequestHeader.Authorization, credentials);

var formData = Encoding.UTF8.GetBytes("grant_type=client_credentials&redirect_uri=" + ruName + "&scope=https://api.ebay.com/oauth/api_scope");
request.ContentLength = formData.Length;


using (var post = request.GetRequestStream())
{
   post.Write(formData, 0, formData.Length);
}

using (var response = request.GetResponse() as HttpWebResponse)
{
   StreamReader reader = new StreamReader(response.GetResponseStream());
   string result = reader.ReadToEnd();
}

但是,以下RestSharp请求返回错误

  

无效请求

var resource = "identity/v1/oauth2/token";
var request = new RestRequest(resource, Method.POST);
var credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(clientId + ":" + clientSecret));
request.AddParameter("Authorization", $"Basic {credentials}", ParameterType.HttpHeader);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
var body = $"grant_type=client_credentials&redirect_uri={ruName}&scope=https://api.ebay.com/oauth/api_scope";
request.AddParameter("text/xml", body, ParameterType.RequestBody);
var client = new RestClient("https://api.sandbox.ebay.com");

return client.Execute<T>(request);

1 个答案:

答案 0 :(得分:1)

以下对我有用,如果你可以更好地解释发生了什么事,那么你的答案是正确的

var resource = "identity/v1/oauth2/token";
var request = new RestRequest(resource, Method.POST);
var credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(clientId + ":" + clientSecret));
request.AddParameter("Authorization", $"Basic {credentials}", ParameterType.HttpHeader);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
var body = $"grant_type=client_credentials&redirect_uri={ruName}&scope=https://api.ebay.com/oauth/api_scope";
var formData = Encoding.UTF8.GetBytes(body);
request.AddParameter("application/x-www-form-urlencoded", formData, ParameterType.RequestBody);
var client = new RestClient("https://api.sandbox.ebay.com");

return GetResult<T>(client, request);

注意行

var body = $"grant_type=client_credentials&redirect_uri={ruName}&scope=https://api.ebay.com/oauth/api_scope";
var formData = Encoding.UTF8.GetBytes(body);
request.AddParameter("application/x-www-form-urlencoded", formData, ParameterType.RequestBody);