C# 中HttpClient无法发送json对象

2021/6/5 12:24:14

本文主要是介绍C# 中HttpClient无法发送json对象,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

使用场景

在C#开发过程中经常会遇到调用API接口的情况,特别是wpf和后台通信。而被调用的接口只接受json字符串。

public String Post(string url, object obj)
{
	using(var client = new HttpClient())
	{
		try
		{
			var str = JsonConvert.SerializeObject(user);
			var content = new StringContent(str,Encoding.UTF8,"application/json");
			HttpResponseMessage response = 
			await client.PostAsync(url, content);
	        response.EnsureSuccessStatusCode();//用来抛异常的
	        string responseBody = await response.Content.ReadAsStringAsync();
	        return responseBody;
	    }catch(Exception ex)
	    {
	    }
	    return null;
}

出现问题

服务器端使用java开发的API,调试发现无法收到传过来的json对象。但是使用Postman调用的时候,服务器端接受正常。

经过wpf端断点调试发现,在传递的content中contentType为 application/text.

解决办法

修改后的代码如下

public String Post(string url, object obj)
{
	using(var client = new HttpClient())
	{
		try
		{
			var str = JsonConvert.SerializeObject(user);
			var content = new StringContent(str,Encoding.UTF8,"application/json");
			content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); //增加这句以后,后台接受正常
			HttpResponseMessage response = 
			await client.PostAsync(url, content);
	        response.EnsureSuccessStatusCode();//用来抛异常的
	        string responseBody = await response.Content.ReadAsStringAsync();
	        return responseBody;
	    }catch(Exception ex)
	    {
	    }
	    return null;
}

增加content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); 后代码正常。

优化

可以把StringContent部分单独列出来作为一个JsonContent类,方便调用。

class JsonContent: StringContent
{
     public JsonContent(object obj) :
        base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
     {
        this.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
     }

}


这篇关于C# 中HttpClient无法发送json对象的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程