问题:近期在使用RestTemplate请求第三方接口时返回?http 411 length required,但postman测试正常。
解决:根据请求参数的大小,手动在RestTemplate设置了请求头ContentLength的长度
headers.setContentLength(jsonObject.toJSONString().getBytes().length);
代码示例如下:
private void setSessionId() throws RuntimeException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", username);
jsonObject.put("password", password);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.setContentLength(jsonObject.toJSONString().getBytes().length);
HttpEntity<JSONObject> httpEntity = new HttpEntity<>(jsonObject, headers);
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(loginUrl, httpEntity, JSONObject.class);
if (responseEntity.getStatusCode().is2xxSuccessful()) {
JSONObject body = responseEntity.getBody();
assert body != null;
sessionId = body.getString("session_id");
log.info("登录接口返回session_id:" + JSONObject.toJSONString(body.getString("session_id")));
} else {
throw new RuntimeException("获取session_id失败!");
}
}
|