阅读来自 HttpClient.GetStringAsync 的回复

Reading the response from HttpClient.GetStringAsync

我正在使用 Windows Phone/Store 应用程序的新运行时开发 Windows 通用应用程序。我正在使用以下代码向服务器发送请求并期待 HTML 响应。然而,当我 return 字符串并将其显示在 UI 中时,它只是说:

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

它没有向我显示应该 return 的实际 HTML/XML。当我在普通 Windows Forms 应用程序中使用相同的 URL 时,它是 returning 我期望的数据但是我在那里使用的代码不同,因为它是 Win32 而不是 WinRT/this 新转发

这是我的代码。我怀疑我没有 return 以正确的格式或其他方式处理数据,但我不知道我应该做什么。

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;
        }

我认为问题不在这段代码中,而在调用者中。我怀疑这段代码在方法 returning 任务中(正确以便调用者可以等待此方法的 HttpClient 调用工作)但调用者没有等待它。

该代码片段看起来正确,并且与 https://msdn.microsoft.com/en-us/library/windows/apps/windows.web.http.httpclient.aspx 的文档基本相同。 GetStringAsync return 是一个任务。 await 将处理 Task 部分并将 return 一个字符串转换为 var 结果。如果您进入函数并检查 result 或 checkResult,它们将是所需的字符串。

来电者也需要做同样的事情。如果这是一个函数

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

然后需要调用await来获取字符串而不是任务并等待GetData的内部await完成:

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

您唯一不会等待任务的情况是您需要操作任务本身而不仅仅是获取结果。

'await' 运算符只能在异步方法中使用。将其 return 类型更改为 Task<string> 应该可以解决问题。 try 块应该是这样的:

try
    {
        Task<string> t = httpClient.GetStringAsync(url);
        string checkResult = t.Result;
        httpClient.Dispose();
        return checkResult;
    }