Search code examples
jsonuwphttpclientwindows-10-universalbackground-task

UWP Httpclient postasync in background task with json string


I would simply like to post some json to an api from a background task in my UWP app and get back the response to read it out. My background task is constantly failing with

Platform::DisconnectedException ^ at memory location 0x077FEE74.

I tried many ways to get it work with things from the internet but only slightly adjusting the failure. Without the code I can execute the background task perfectly.

Here the code:

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)");

StringContent theContent = new StringContent("{ \"keep_login\": true, \"id\": null, \"username\": \"zumbauser\", \"password\": \"zumbapw\" }", Encoding.UTF8, "application/json");


        HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);

        if (aResponse.IsSuccessStatusCode)
        {
            Debug.WriteLine("This is outpuuuuuuuuuuuuuut: " + aResponse.ToString());
        }
        else
        {
            // show the response status code 
            String failureMsg = "HTTP Status: " + aResponse.StatusCode.ToString() + " – Reason: " + aResponse.ReasonPhrase;
        }

_deferral.Complete();
        }

The Json I am trying to imitate looks something like this:

{"keep_login":null,"id":null,"username":"zumbauser","password":"zumbapw"}

Any help is appreciated!


Solution

  • 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.