为什么使用 Postman 向控制器发送请求运行正常,但使用 RestTemplate 会抛出 500 Internal Server Error?

Why sending a request to controller using Postman runs fine but using RestTemplate throws 500 Internal Server Error?

上下文

我有两个控制器:/testParams/callTestParams 控制器 /testParams 收到类型为 Example 的 object,我可以毫无问题地从 Postman 调用此控制器。

控制器 /callTestParams 使用 RestTemplate 在内部调用 /testParams 但响应是 500 内部服务器错误。我假设 /callTestParams 的实现等同于 Postman 的调用。

代码如下:

@RequestMapping(value = "/testParams",
            method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
    public ResponseEntity<Object> testParams(            
            @RequestBody Example credentials
    ) {


        JSONObject params = new JSONObject( credentials );

        System.out.println( params.get("clientId") + " from JSONObject");
        System.out.println( credentials.getClientId() + " from GraphCredentials");


        return new ResponseEntity<>(credentials,HttpStatus.OK);
    }




    @RequestMapping(value = "/callTestParams",
            method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
    public ResponseEntity<Object> callTestParams() {

        String url = "http://localhost:8080/GraphClient/testParams";

        HttpHeaders headers = new HttpHeaders();

        headers.set( HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE );

        JSONObject params = new JSONObject();
        params.put("clientId", "value1" );

        RestTemplate restTemplate = new RestTemplate();

        HttpEntity<?> entity = new HttpEntity<>(params,headers);

        HttpEntity<Object> response = restTemplate.exchange(
          url,
          HttpMethod.POST,
          entity,
          Object.class
        );

        return new ResponseEntity<>(response.getBody(), HttpStatus.OK);
    }

这是 Postman 对 /testParams 的响应

Headers: (Content-Type,application/json)

请求Body: JSON (appplication/json)

{"clientId":"value1"}

响应:

{
    "clientId": "value1",
    "clientSecret": null,
    "tenantId": null,
    "scope": null,
    "grantType": null,
    "microsoftLoginBaseURL": "https://login.microsoftonline.com/"
}

这是 Postman 对 /callTestParams 的响应

{
    "timestamp": "2022-01-09T03:39:06.878+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "500 Internal Server Error",
    "path": "/GraphClient/callTestParams"
}

这是控制台的错误>

由于未找到异常 [JSONObject["clientId"],从请求 [/testParams] 转发到错误页面。]:org.json.JSONException:JSON Object["clientId"] 未找到。

在 HttpEntity 构造函数的主体参数中,您需要将参数作为字符串传递

HttpEntity<?> entity = new HttpEntity<>(params.toString(),headers);