在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"); } }