【问题标题】:Get JSON string with httpClient使用 httpClient 获取 JSON 字符串
【发布时间】:2014-10-01 05:02:12
【问题描述】:

我正在使用 Xamarin Forms,我正在尝试获取位于此处的文件的 JSON 字符串。但是我似乎无法取出 Json 字符串。这是我的代码:

public async static Task<string> GetJson(string URL)
{
    using (HttpClient client = new HttpClient())
    using (HttpResponseMessage response = await client.GetAsync(URL))
    using (HttpContent content = response.Content)
    {
        // ... Read the string.
        return await content.ReadAsStringAsync();
    }
}

private static void FindJsonString()
{
    Task t = new Task(GetJson("https://dl.dropboxusercontent.com/u/37802978/policyHolder.json"));
    t.Start();
    t.Wait();
    string Json = t.ToString();
}

我做错了什么?

我得到与这条线有关的这 2 个错误

Task t = new Task(GetJson("https://dl.dropboxusercontent.com/u/37802978/policyHolder.json"));

错误 1
'System.Threading.Tasks.Task.Task(System.Action)' 的最佳重载方法匹配有一些无效参数

错误 2
参数 1:无法从 'System.Threading.Tasks.Task' 转换为 'System.Action'

【问题讨论】:

标签: c# .net json async-await httpclient


【解决方案1】:

那是因为 new Task 期待一个 Action 委托,而您将它传递给 Task&lt;string&gt;

不要使用new Task,使用Task.Run。另外,请注意您正在传递 async 方法,您可能想要 await GetJson

所以你要么需要

var task = Task.Run(() => GetJson("https://dl.dropboxusercontent.com/u/37802978/policyHolder.json"));

或者如果你想在Task.Run里面await

var task = Task.Run(async () => await GetJson("https://dl.dropboxusercontent.com/u/37802978/policyHolder.json"));

它们的返回类型也会不同。前者将返回Task&lt;Task&lt;string&gt;&gt;,而后者将返回Task&lt;string&gt;

TPL 指南规定异步方法应以 Async 后缀结尾。考虑将GetJson 重命名为GetJsonAsync

【讨论】:

  • 感谢您回答@Yuval。但是如何从 GetJson 获取返回字符串?是否在 var 任务中?
  • await 在语义上从返回类型中删除任务。所以,await GetJson() 是 Json 字符串。在任务上调用.Result 也将完成相同的结果,但会阻塞您的线程。
  • Task.Run 运行ti 补全时,您可以在task.Result 中访问它。请注意,如果您在任务完成之前访问 Result 属性,它将像同步方法一样阻塞
猜你喜欢
  • 2018-08-03
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 2017-02-22
  • 2022-01-09
相关资源
最近更新 更多