我在Spring Boot中做了一个post请求并用postman测试它,但是当我在Postman中传递body并尝试在我的应用程序中读取它时,它会抛出错误。 这是Spring中的方法:
@PostMapping(path=PathConstants.START_ACTION)
public String start(@PathVariable String processDefinitionId, @RequestBody(required=false) String params){
if(params!=null) {
Gson gson = new Gson();
Map<String,Object> pvar = gson.fromJson(params, Map.class);
System.out.println(pvar);
}
}
在Postman中,我通过这种方式传递params:
我在标题中指定了内容类型为application/json
。
但是,如果我使用“Param”标签传递我的参数
有用。但我需要将它们作为身体传递而不是传递。这里的问题在哪里?
方法1:
标题Content-Type
是application-json
。所以Spring尝试将你的json
构建成LinkedHashMap
。
现在,试试这个......
@PostMapping(path=PathConstants.START_ACTION)
public String start(@PathVariable String processDefinitionId, @RequestBody(required=false) Map<String, Object> bodyObject){
if(MapUtils.isNotEmpty(bodyObject)) {
Map<String,Object> pvar = bodyObject;
}
代替
@PostMapping(path=PathConstants.START_ACTION)
public String start(@PathVariable String processDefinitionId, @RequestBody(required=false) String params){
if(params!=null) {
Gson gson = new Gson();
Map<String,Object> pvar = gson.fromJson(params, Map.class);
System.out.println(pvar);
}
}
并通过header
content-type
作为application/json
。这会工作..
方法2 ::
现在,如果您仍想使用自己的旧签名方法,请执行此操作。
@PostMapping(path=PathConstants.START_ACTION)
public String start(@PathVariable String processDefinitionId, @RequestBody(required=false) String params){}
然后在header
content-type
作为text/plain
。然后你的旧方法也会工作..