apache / servicecomb-java-chassis

ServiceComb Java Chassis is a Software Development Kit (SDK) for rapid development of microservices in Java, providing service registration, service discovery, dynamic routing, and service management features
Apache License 2.0
1.91k stars 813 forks source link

body传递raw json/接收raw json #3254

Closed yyshiningyear closed 2 years ago

yyshiningyear commented 2 years ago

body传递raw json的方式

业务需要调用一个三方接口,需要传递raw json,根据这个帖子的指导:https://bbs.huaweicloud.com/forum.php?mod=viewthread&tid=6797 声明@RawJsonRequestBody是可行的:

// 接口声明(这个是本地调用第三方接口,将其注册在本地的契约)
    @RequestMapping(value = "/service", produces = {"application/json"},
        consumes = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    JSONObject getResult(@RequestHeader("Authorization")String authHeader, @RawJsonRequestBodyString body);

// 接口调用
String bodyJson = JSON.toJSONString(reqPara);
JSONObject obj = mepClientApi.getResult("header", bodyJson);

调用正常返回;

但是另一种方式 “Consums声明为text/plain”测试时报错

// 接口声明(这个是本地调用第三方接口,将其注册在本地的契约)
    @RequestMapping(value = "/service", produces = {"application/json"},
        consumes = {"text/plain;charset=UTF-8"}, method = RequestMethod.POST)
    JSONObject getResult(@RequestHeader("Authorization")String authHeader, @RequestBody String body);

// 接口调用
String bodyJson = JSON.toJSONString(reqPara);
JSONObject obj = mepClientApi.getResult("header", bodyJson);

服务端返回的错误信息为 syntax error, expect {, actual string, pos 0, fastjson-version 1.2.76 ,根据这个错误信息,判断是服务端在解析json时发现是传过去的body是包了引号的数据 “{}”;这种方式是不是我用的有问题?

接收raw json格式的响应体

业务希望将该三方接口返回的字符串直接作为json使用,按照帖子的指导将produces声明为text/plain,测试时也有问题:

// 接口声明(这个是本地调用第三方接口,将其注册在本地的契约)
    @RequestMapping(value = "/service", produces = {"text/plain"},
        consumes = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    String getResult(@RequestHeader("Authorization")String authHeader, @RawJsonRequestBodyString body);

// 接口调用
String bodyJson = JSON.toJSONString(reqPara);
String resJson = mepClientApi.getResult("header", bodyJson);

请求报错 CommonExceptionData [message=method POST, path /service/, statusCode 200, reasonPhrase , response content-type application/json is not supported] ,这是什么原因呢?

yyshiningyear commented 2 years ago
  1. body传递raw json 和三方服务接口的开发人员看了一下,他们接口里声明的consumer是“application/json”,所以在调用方传递 “text/plain”是不行的

  2. 接收raw json格式的响应体 同样看了下三方服务的接口,他们使用的是 @RestController 注解,该注解默认会将返回pojo类型的接口的produces设置为 application/json,所以业务使用text/plain无法接收