用c#创建Postman请求



我能够在Postman中提出以下请求,但不能在c#中。我猜这是由于json,但尝试了几种不同的方法,仍然没有。

邮差:

curl --location --request POST 'https://login.sandbox.payoneer.com/api/v2/oauth2/token' 
--header 'Authorization: Basic *ENCRYPTEDPASSCODE FROM ClientID & Secret*' 
--header 'Content-Type: application/x-www-form-urlencoded' 
--data-urlencode 'grant_type=client_credentials' 
--data-urlencode 'scope=read write'

我的代码返回text "ErrorParams":null:

var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"https://login.sandbox.payoneer.com/api/v2/oauth2/token");
var authString = $"{clientID}:{secret}";
var encodedString = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(authString));
request.Headers.Add("Authorization", $"Basic {encodedString}");
string json = JsonConvert.SerializeObject(new
{
grant_type = "client_credentials",
scope = "read write"
});
request.Content = new StringContent(json, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = await client.SendAsync(request).ConfigureAwait(false);
var responseText = await response.Content.ReadAsStringAsync();
return responseText;

如果您需要将内容设置为application/x-www-form-urlencoded,则使用FormUrlEncodedContent

var dict = new Dictionary<string, string>();
dict.Add("grant_type", "client_credentials");
dict.Add("scope", "read write");
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"https://login.sandbox.payoneer.com/api/v2/oauth2/token") { Content = new FormUrlEncodedContent(dict) };
var response = await client.SendAsync(request).ConfigureAwait(false);
var responseText = await response.Content.ReadAsStringAsync();

如果要将请求体序列化为JSON,则需要将Content-Type设置为application/json

request.Headers.Add("Content-Type", "application/json");

相关内容

最新更新