我正在使用 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"));
Error 1
The best overloaded method match for 'System.Threading.Tasks.Task.Task(System.Action)' has some invalid argumentsError 2
Argument 1: cannot convert from 'System.Threading.Tasks.Task' to 'System.Action'
最佳答案
那是因为new Task
期待 Action
代表,当你传递一个 Task<string>
时.
不要使用new Task
,使用Task.Run
。另请注意,您传递的是 async
方法,您可能想要await GetJson
:
所以你要么需要
var task = Task.Run(() => GetJson("https://dl.dropboxusercontent.com/u/37802978/policyHolder.json"));
或者如果你想 await
里面Task.Run
:
var task = Task.Run(async () => await GetJson("https://dl.dropboxusercontent.com/u/37802978/policyHolder.json"));
它们的返回类型也有所不同。前者将返回 Task<Task<string>>
,而后者将返回 Task<string>
TPL 指南规定异步方法应以 Async
结尾后缀。考虑重命名 GetJson
至GetJsonAsync
.
关于c# - 使用 httpClient 获取 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26134425/