Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading the response from HttpClient.GetStringAsync

I am working on a Windows Universal app using the new runtime for Windows Phone/Store apps. I am sending a request to a server using the following code and expecting a HTML response back. However when I return the string and display it in the UI, it just says:

"System.Threading.Tasks.Task'1[System.String]"

It's not showing me the actual HTML/XML that should be returned. When I use the same URL in a normal Windows Forms app, it's returning the data I expect but the code I use there is different due to it being Win32 not WinRT/this new RT.

Here's my code. I suspect I am not returning the data in the right format or something but I don't know what I should be doing.

var url = new Uri("http://www.thewebsitehere.com/callingstuff/calltotheserveretc");
var httpClient = new HttpClient();

        try
        {
            var result = await httpClient.GetStringAsync(url);
            string checkResult = result.ToString();
            httpClient.Dispose();
            return checkResult;
        }
        catch (Exception ex)
        {
            string checkResult = "Error " + ex.ToString();
            httpClient.Dispose();
            return checkResult;
        }
like image 630
irldev Avatar asked Feb 14 '15 16:02

irldev


1 Answers

I don't think the problem is in this code snippet but in the caller. I suspect this code is in a method returning a Task (correct so that the caller can wait for this method's HttpClient call to work) but that the caller isn't awaiting it.

The code snippet looks correct and essentially the same as in the docs at https://msdn.microsoft.com/en-us/library/windows/apps/windows.web.http.httpclient.aspx . GetStringAsync returns a Task. The await will handle the Task part and will return a string into var result. If you break inside the function and examine result or checkResult they'll be the desired strings.

The same thing needs to happen with the caller. If this is in a function

Task<string> GetData() 
{
    // your code snippet from the post 
    return checkResult; // string return is mapped into the Task<string>
}

Then it needs to be called with await to get the string rather than the task and to wait for GetData's internal await to finish:

var v = GetData(); // wrong <= var will be type Task<string>
var data = await GetData(); // right <= var will be type string

The only time you wouldn't await the Task is if you need to manipulate the Task itself and not just get the result.

like image 130
Rob Caplan - MSFT Avatar answered Oct 13 '22 21:10

Rob Caplan - MSFT