UWP Httpclient postasync in background task with json string UWP Httpclient postasync in background task with json string json json

UWP Httpclient postasync in background task with json string


I know this might sound silly, but which HttpClient are you using? The one from System.Net.Http or the one from Windows.Web.Http? Try switching to the other one, it might help


It would be preferrable to use windows.web.http.httpclient for UWP apps since it supports wide range of Languages. See table from the reference

Now for StringContent. Windows.Web.HttpClient as HttpStringContent which is similar to StringContent in System.Net.Http.HttpClient

This is a snippet for example but make sure you read the reference.

Uri theUri = new Uri("https://m.xxxx.com/api/v4/session?expand=account,profile)");HttpStringContent content = new HttpStringContent("{ \"keep_login\": true, \"id\": null, \"username\": \"zumbauser\", \"password\": \"zumbapw\" }", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");var client = new HttpClient();HttpResponseMessage response = await client.PostAsync(theUri, content);

So to complete your Method it will be

public async void Run(IBackgroundTaskInstance taskInstance){    _deferral = taskInstance.GetDeferral();    HttpClient aClient = new HttpClient();    aClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));    aClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/javascript"));    Uri theUri = new Uri("https://m.xxxx.com/api/v4/session?expand=account,profile)");    HttpStringContent content = new HttpStringContent("{ \"keep_login\": true, \"id\": null, \"username\": \"zumbauser\", \"password\": \"zumbapw\" }", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");    HttpResponseMessage aResponse = await aClient.PostAsync(theUri, content);    if (aResponse.IsSuccessStatusCode)    {        Debug.WriteLine("This is outpuuuuuuuuuuuuuut: " + aResponse.ToString());    }    else    {        String failureMsg = "HTTP Status: " + aResponse.StatusCode.ToString() + " – Reason: " + aResponse.ReasonPhrase;    }    _deferral.Complete();}

Note: I tried the same with one of my APP in a background task and it works fine. only case it failed was when i tried to send huge data i got Not enough memory available error.

Good Luck and Happy Coding.