简体   繁体   English

在C# winform中获取数据JSON

[英]Get data JSON in C# winform

I want to get 2 data like "phone" and "username" from this URL: "http://localhost/api/basic.php?id={id}" in C#我想从这个 URL 中获取 2 个数据,例如“电话”和“用户名”:C# 中的“http://localhost/api/basic.php?id={id}”

I Use this code to get我使用此代码获取

string api = "http://localhost/api/basic.php?id=";
api += TxtID.Text;
WebClient client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(api);
myHttpWebRequest.Referer = "http://localhost/api/form.html";

The modern way (for .net 5 and 4.x) is:现代方式(对于 .net 5 和 4.x)是:

using System.Net.Http.Json;  // add the NuGet package

private HttpClient client = new HttpClient();
private async void MyForm_Load(object sender, EventArgs e)
{           
    MyClass data = await client.GetFromJsonAsync<MyClass>(api);
    ...
}

do not Dispose the HttpClient.不要处置 HttpClient。

The package is not part of the default WinForms template, add System.Net.Http.Json from NuGet. package 不是默认 WinForms 模板的一部分,从 NuGet 添加System.Net.Http.Json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM