簡體   English   中英

在C# winform中獲取數據JSON

[英]Get data JSON in C# winform

我想從這個 URL 中獲取 2 個數據,例如“電話”和“用戶名”:C# 中的“http://localhost/api/basic.php?id={id}”

我使用此代碼獲取

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";

現代方式(對於 .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);
    ...
}

不要處置 HttpClient。

package 不是默認 WinForms 模板的一部分,從 NuGet 添加System.Net.Http.Json

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM