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对象的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID
- 2024-01-23用CI/CD工具Vela部署Elasticsearch + C# 如何使用
- 2024-01-23.NET开源的简单、快速、强大的前后端分离后台权限管理系统