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

标签 c# .net json async-await httpclient

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

相关文章:

javascript - 如何在每个动态创建的 ImageButton 周围包裹一个超链接? Visual Studio

c# - 如果缺少 DTD,XML DocumentType 方法 CreateDocumentType 会崩溃 .NET C#

c# - 手动在 datagridview 上添加行

c# - Console.Write 在由 .NET GUI 应用程序的 BackgroundWorker 执行时不起作用

.net - Graphics.DrawRectangle 在第二个屏幕上缺少边缘

.net - 用于检测 .NET CF 3.5 并安装它的 Windows Mobile Cab 设置

c# - 如何将 CancellationTokenSource 附加到 DownloadStringTaskAsync 方法并取消异步调用?

javascript - 从 json 中获取从特定索引开始的字符串值

javascript - 使用循环返回嵌套 json 值(谷歌电子表格)

python - 我想使用 TOTP 将我的响应发送到 API?