5

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!

SunnySonic
  • 1,318
  • 11
  • 37

2 Answers2

1

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

Tomáš Bezouška
  • 1,395
  • 1
  • 10
  • 25
  • I'm using system.net.http cause StringContent is only available for that. How can I rewrite it for Windows.web.http ? – SunnySonic Sep 07 '16 at 14:47
1

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.

AVK
  • 3,893
  • 1
  • 22
  • 31
  • Thanks. Trying it now in variations. The "MediaTypeWithQualityHeaderValue" though is also part of the system.net.http api. VS2015 suggested me to change it to Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue. Will report back... – SunnySonic Sep 09 '16 at 19:39
  • Exception thrown: 'System.IO.FileLoadException' in mscorlib.ni.dll The program '[14704] backgroundTaskHost.exe' has exited with code 1 (0x1). That's all i get when i add the code. without the code it runs fine. :( There seems to be some other issue too... – SunnySonic Sep 09 '16 at 19:45
  • Are you loading something from a File Here? – AVK Sep 09 '16 at 19:49
  • No. Nothing. That's the weird part. The background task is completely empty, besides the code. Has it something to do with the stream that needs a certain memory access? – SunnySonic Sep 09 '16 at 21:21
  • Are you serializing Json from a Class object using Newtonsoft Json? If yes, then try to uninstall the package and install it. I had the same issue around 2 months back and doing this fixed my problem. – AVK Sep 09 '16 at 21:45
  • I had it installed before now that you are saying it but de-installed it after again. Will try to reinstall and then delete again... – SunnySonic Sep 10 '16 at 14:49
  • After installing and deinstalling the nuget package for Newtonsoft Json the code runs sort of in the background task. I can tell that by the Debug writelines that i put before my method which was'nt executed before. Nevertheless i still don't get a response from the "postasync". Still getting this only on mobile device and on pc.: The program '[11828] backgroundTaskHost.exe' has exited with code 1 (0x1). Exception thrown: 'System.Exception' in mscorlib.ni.dll – SunnySonic Sep 10 '16 at 15:06
  • Hi! Somehow your code does not work for me. Please take a lokk to my question https://stackoverflow.com/questions/54759390/exception-thrown-system-typeloadexception-in-unknown-module-in-uwp-background – NoWar Feb 19 '19 at 06:35