通过Httpclient

时间:2016-10-05 02:33:02

标签: c# paypal xamarin.forms httpclient

我试图通过Xamarin Forms使用PayPal RESTful API,并在尝试获取OAuth令牌时遇到麻烦。这是我正在运行的代码,在Android上发生错误。我在这里更改了身份验证标头,以便我的客户端ID和密码不公开。这是我基于此HTTP请求的curl命令:https://developer.paypal.com/docs/integration/direct/make-your-first-call/。谢谢。

var getToken = new HttpClient(new NativeMessageHandler());
getToken.BaseAddress = new Uri("https://api.sandbox.paypal.com/v1/oauth2/token");
getToken.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
getToken.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("en_US"));
getToken.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("**client_id**", "**secret**");
getToken.DefaultRequestHeaders.TryAddWithoutValidation("content-type", "application/x-www-form-urlencoded");

OAuthDetails clientCredentials = new OAuthDetails("client_credentials");
HttpResponseMessage tokenResponse = await getToken.PostAsJsonAsync("/v1/oauth2/token", clientCredentials);
AccessResponse accessInfo = await tokenResponse.Content.ReadAsAsync<AccessResponse>();

1 个答案:

答案 0 :(得分:0)

使用application / x-www-form-urlencoded发送帖子请求的方式是这样的:您需要执行此操作而不是TryAddWithoutValidation,然后将此作为请求中的内容而不是我之前使用的客户端凭据

var tokenContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("grant_type", "client_credentials"
});