Winform中使用HttpClient實現呼叫http的post介面並設定傳參content-type為application/json示例

霸道流氓發表於2024-07-04

場景

Winform中怎樣使用HttpClient呼叫http的get和post介面並將介面返回json資料解析為實體類:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/124157296

上面使用HttpClient呼叫post介面時使用的HttpContent的格式為 application/x-www-form-urlencoded

對應的程式碼實現

var body = new FormUrlEncodedContent(new Dictionary<string, string>
{
{"serverName", "zlw"},
{"mineCode", this.textBox_mineCode.Text.Trim().ToString()},
{"targetServer",this.textBox_targetServer.Text.Trim().ToString()},
{"port", this.textBox_port.Text.Trim().ToString()},
{"user", this.textBox_user.Text.Trim().ToString()},
{"pass", this.textBox_pass.Text.Trim().ToString()},
{"dir", this.textBox_dir.Text.Trim().ToString()},
{"filePath", this.textBox_filePath.Text.Trim().ToString()},
});
// response
var response = httpClient.PostAsync(url, body).Result;

如果呼叫介面時明確指出必須是application/json格式,則需要修改程式碼實現方式。

注:

部落格:
https://blog.csdn.net/badao_liumang_qizhi

實現

1、以呼叫若依框架的登入介面為例,需要傳遞application/json的使用者名稱和密碼引數

這裡為快速實現,所以手動構造和轉義json字串

var jsonContent = "{\"username\":\"bGVk\",\"password\":\"MTIzNDU2Nzg=\"}";

實際使用時需要使用正規的json序列化工具等方式。

然後content不再是FormUrlEncodedContent,而是StringContent

var content = new StringContent(jsonContent, Encoding.UTF8, "application/json")

然後傳參時

var response = httpClient.PostAsync(url, content).Result;

2、完整示例程式碼

var httpClient = new HttpClient();
var url = new Uri("http://127.0.0.1:192/prod-api/login");
var jsonContent = "{\"username\":\"bGVk\",\"password\":\"MTIzNDU2Nzg=\"}";
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
var response = httpClient.PostAsync(url, content).Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content.ReadAsStringAsync();
var data = responseContent.Result;
Console.WriteLine(data);
JavaScriptSerializer js = new JavaScriptSerializer();//例項化一個能夠序列化資料的類
LoginResult result = js.Deserialize<LoginResult>(data);
Console.WriteLine(result.token);
}
}

後面的部分則是讀取返回值並序列化為實體類

其中實體類LoginResult為

class LoginResult
{
/// <summary>
/// 操作成功
/// </summary>
public string msg { get; set; }

/// <summary>
///
/// </summary>
public int code { get; set; }

/// <summary>
///
/// </summary>
public string token { get; set; }
}

測試結果

相關文章