在c#的Winform應用程序中,面對Http請求和Json數據的處理,我們可以使用如下方法:
首先,我們需要添加引用System.Net和System.Net.Http的命名空間。其次,我們可以使用HttpClient來發送Http請求,并使用JsonConvert來序列化和反序列化Json數據。
using System.Net; using System.Net.Http; using Newtonsoft.Json; //發送HttpGet請求,并返回服務器響應 public static async TaskSendHttpGet(string url) { HttpClient httpClient = new HttpClient(); HttpResponseMessage response = await httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); return responseBody; } //發送HttpPost請求,并返回服務器響應 public static async Task SendHttpPost(string url, Dictionary<string, string> parameters) { HttpClient httpClient = new HttpClient(); HttpContent httpContent = new FormUrlEncodedContent(parameters); HttpResponseMessage response = await httpClient.PostAsync(url, httpContent); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); return responseBody; } //將Json字符串反序列化為對象 public static T JsonDeserialize<T>(string json) { T obj = JsonConvert.DeserializeObject<T>(json); return obj; } //將對象序列化為Json字符串 public static string JsonSerialize(object obj) { string json = JsonConvert.SerializeObject(obj); return json; }
以上代碼示例展示了如何使用HttpClient發送HttpGet和HttpPost請求,并使用JsonConvert進行對象和Json字符串之間的序列化和反序列化。
上一篇vue css控制