locked
C# post request with Json response

    Question

  • Hello, I'm trying to create a Windows Store app that sends a post request to a web server, then the web server will return a json response. I did the post request working but I don't succeed in getting the json response.

    Here is a code example:

    var client = new System.Net.Http.HttpClient();
    
    var requestContent = new FormUrlEncodedContent(new[] {
                    new KeyValuePair<string, string>("username", "user"),
                    new KeyValuePair<string, string>("password", "pass"),
                });
    
    System.Net.Http.HttpResponseMessage response = await client.PostAsync(
                    "http://url.com",
                    requestContent);
    
                // Get the response content.
    
                HttpContent responseContent = response.Content;
    
                // Get the stream of the content.
                using (var streamReader = new StreamReader(await responseContent.ReadAsStreamAsync()))
                {
                    // Write the output.
                    
                    var msg = new Windows.UI.Popups.MessageDialog(await response.Content.ReadAsStringAsync());
                    await msg.ShowAsync();
                }

    In the messagedialog I get a sign like this: 

    When I perform following code instead of showing the messagedialog:

    JsonObject jsonObject = JsonObject.Parse(await response.Content.ReadAsStringAsync());

    I get this error:
    WinRT information: Invalid character at position 0.
    
    Additional information: Invalid JSON string.
    
    
    
    Invalid character at position 0.
    
    If there is a handler for this exception, the program may be safely continued.

    Thanks
    Saturday, May 24, 2014 1:11 PM

Answers

  • Thanks for your answer but the problem is already solved, the JSon output was encoded with gzip.

    thanks

    • Marked as answer by DaanLenaerts Sunday, May 25, 2014 10:40 AM
    Sunday, May 25, 2014 10:39 AM

All replies

  • What is the web service suppose to be sending back?  I am wondering if you are just getting back a http status like ok.  If there is no text sent back you will not be able to read it in
    Saturday, May 24, 2014 4:02 PM
  • Thanks for your answer but the problem is already solved, the JSon output was encoded with gzip.

    thanks

    • Marked as answer by DaanLenaerts Sunday, May 25, 2014 10:40 AM
    Sunday, May 25, 2014 10:39 AM
  • If you use the Windows.Web.Http version of HttpClient, it will automatically unzip the content by default. The System.Net one can unzip content for you, but you need to enable it first.

    Take a look at http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler(v=vs.118).aspx and set the AutomaticDecompression flag.


    Network Developer Experience Team (Microsoft)

    Tuesday, May 27, 2014 8:11 PM
  • Thanks
    Tuesday, May 27, 2014 8:13 PM