Reputation: 113
How to set up a Windows.Web.Http.HttpClient PostAsync with basic authorization and mediatype in addition to key/value pairs in Json?
I cannot find any good documentation or examples on how to do this.
These official sites offer very little documentation on how to solve this: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.web.http.httpclient.aspx
Help appreciated! Thanks!
Upvotes: 2
Views: 2062
Reputation: 113
I found an solution that worked for me:
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("client_id", Constants.CLIENT_ID);
pairs.Add("grant_type", "authorization_code");
pairs.Add("code", code);
var formContent = new HttpFormUrlEncodedContent(pairs);
var base64Creds = Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes(string.Format("{0}:{1}", Constants.CLIENT_ID, Constants.CLIENT_SECRET)));
var httpFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
httpFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
var client = new HttpClient(httpFilter);
client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Basic", base64Creds);
HttpResponseMessage response = await client.PostAsync(new Uri(Constants.GET_TOKEN_URL), formContent);
client.Dispose();
Upvotes: 2
Reputation: 1967
You can try something like this
HttpClient client = new HttpClient();
string jsonContent = JsonConvert.SerializeObject(YourObject);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationTokenString);
StringContent theContent = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage aResponse = await client.PostAsync(new Uri(UrlValue), theContent);
string responseContent = await aResponse.Content.ReadAsStringAsync();
client.Dispose();
Edit : The above code is using System.Net.Http.HttpClient
But if you would like to use Windows.Web.Http.HttpClient
check out this link
Upvotes: 0