场景
Winform中怎样使用HttpClient调用http的get和post接口并将接口返回json数据解析为实体类:
Winform中怎样使用HttpClient调用http的get和post接口并将接口返回json数据解析为实体类_winform解析json-CSDN博客
上面使用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; }
}
测试结果