gpt4 book ai didi

c# - 使用 httpClient 获取 JSON 字符串

转载 作者:太空宇宙 更新时间:2023-11-03 10:39:07 25 4
gpt4 key购买 nike

我正在使用 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 arguments

Error 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 结尾后缀。考虑重命名 GetJsonGetJsonAsync .

关于c# - 使用 httpClient 获取 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26134425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com