Ethan Williams Ethan Williams - 4 months ago 41
C# Question

System.TypeLoadException when submitting HTTP request through Httpclient

I am attempting to use the PayPal RESTful API through Xamarin Forms and am running into trouble when I try and obtain the OAuth token. Here is the code I am running, and error occurs when on Android. The authentication header I have changed here so that my client id and secret are not openly available. This is the curl command I am basing this HTTP request on also: Thank you.

var getToken = new HttpClient(new NativeMessageHandler());
getToken.BaseAddress = new Uri("");
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>();


The way to send a post request with application/x-www-form-urlencoded is like this: instead of TryAddWithoutValidation you need to do this and then include this as the content in the request instead of client credentials like I did previously.

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