1

I'm trying to make some post Request on an existing API.

I tried to use that API using the plugin Postman on chrome and it works pretty well.

Now i have to make those calls from my windows phone app in c#.

As you see it works.

Now here is what i tried to do at first in C# using HttpClient:

(I of course instanciate _httpClient and BaseAdress in the Ctor)

        this._httpClient.DefaultRequestHeaders.Accept.Clear();
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("client_id:client_secret");
        var encodedAuth = System.Convert.ToBase64String(plainTextBytes);
        this._httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(encodedAuth);
        var formContent = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "client_credentials") 
        });
        var res = await _httpClient.PostAsync("/oauth/token", formContent);

It won't work, i got a FormatException.

Then i looked over the internet and found some answers, people saying that i should use the regular header and add it manually, so here is what i did.

        this._httpClient.DefaultRequestHeaders.Accept.Clear();
        this._httpClient.DefaultRequestHeaders.Add("Authorization", "Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=");
        var formContent = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "client_credentials") 
        });
        var res = await _httpClient.PostAsync("/oauth/token", formContent);

I get the same exception.

The header Authorization is actually client_id:client_secret encoded in Base64 which is a requirment of that API.

So if Someone could provide some help that'd be nice :)

Thank you for reading and helping. Guillaume.

bottus
  • 883
  • 2
  • 13
  • 32

1 Answers1

0

I finally managed to find a solution but i'm not sure about it.

I add to replace :

this._httpClient.DefaultRequestHeaders.Add("Authorization", "Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=");

By

this._httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=");

thanks to Antonio Here

Community
  • 1
  • 1
bottus
  • 883
  • 2
  • 13
  • 32