Java Json未通过Unirest.post发送
我试图通过一个测试类中的Unirest.post()发送一个Json对象,我得到了一个到URL的工作连接,但得到的异常是没有传输Json对象。包括以下API调用代码:Java Json未通过Unirest.post发送,java,json,unirest,Java,Json,Unirest,我试图通过一个测试类中的Unirest.post()发送一个Json对象,我得到了一个到URL的工作连接,但得到的异常是没有传输Json对象。包括以下API调用代码: try{ String location = "http://localhost:" + port + "/check-person"; System.out.println(location); HttpResponse<JsonNode> jsonResponse
try{
String location = "http://localhost:" + port + "/check-person";
System.out.println(location);
HttpResponse<JsonNode> jsonResponse =
Unirest.post("http://localhost:" + port + "/check-person")
.body("{\"personName\": \"Darth Vader\"}")
.asJson();
assertEquals(403, jsonResponse.getStatus());
} catch(UnirestException e){
e.printStackTrace();
System.out.println(e);
}
试试看{
字符串位置=”http://localhost:“+端口+”/检查人”;
系统输出打印项次(位置);
HttpResponse jsonResponse=
Unirest.post(“http://localhost:“+端口+”/检查人”)
.body(“{\”人名\“:\”达斯维德\“}”)
.asJson();
assertEquals(403,jsonResponse.getStatus());
}捕获(unireste异常){
e、 printStackTrace();
系统输出打印ln(e);
}
将内容类型
作为JSON包含在标题中。这将告诉服务器应该将主体解释为JSON。一些常见的类型如下
“application/json”、“application/xml”、“text/html”、“text/plain”
在UniRest请求中添加内容类型标头,如中所示
try{
String location = "http://localhost:" + port + "/check-person";
System.out.println(location);
HttpResponse<JsonNode> jsonResponse =
Unirest.post("http://localhost:" + port + "/check-person")
.header("Content-Type", "application/json")
.body("{\"personName\": \"Darth Vader\"}")
.asJson();
assertEquals(403, jsonResponse.getStatus());
} catch(UnirestException e){
e.printStackTrace();
System.out.println(e);
}
试试看{
字符串位置=”http://localhost:“+端口+”/检查人”;
系统输出打印项次(位置);
HttpResponse jsonResponse=
Unirest.post(“http://localhost:“+端口+”/检查人”)
.header(“内容类型”、“应用程序/json”)
.body(“{\”人名\“:\”达斯维德\“}”)
.asJson();
assertEquals(403,jsonResponse.getStatus());
}捕获(unireste异常){
e、 printStackTrace();
系统输出打印ln(e);
}
尝试通过Unirest.post(“:”+port+“/check person”).header(“内容类型”、“应用程序/json”)在header中设置内容类型。包括异常日志,以便其他人可以找出错误。感谢您的快速回答,这解决了问题。