获取异常org.springframework.web.client.HttpClientErrorException:


public String getOrderdata(final String poNumber) throws Exception {
String apiResponse = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
String url = ApiHost + ApiPath;
JSONObject requestJson = new JSONObject();
requestJson.put("orderNumber", poNumber);
HttpEntity<String> request = new HttpEntity<>(requestJson.toString(), getHttpHeaders());
log.info("request is " + request);
log.info("Api url={}", url);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
log.info("Inside ServiceImpl, response is {}", response);
if (response != null && response.hasBody() && response.getStatusCode() == HttpStatus.OK) {
apiResponse = objectMapper.readValue(response.getBody(), String.class);
} else if (response != null && response.getStatusCode() == HttpStatus.BAD_REQUEST) {
log.info("event=getOrderdata: Received bad request exception from Api and Response is {} : ", response);
} else {
log.error("event=getOrderdata: Response is null= {} : ", response);
throw new RuntimeException("Error While fetching details from api");
}
} catch (HttpClientErrorException e) {
log.info("event=getOrderdata: HttpClientErrorException error=", e);
} catch (Exception exe) {
log.error("event=getOrderdata: error=", exe);
//throw exe;
}
return apiResponse;
}
public HttpHeaders getHttpHeaders() {
HttpHeaders headers = new HttpHeaders();
try {
val token = Client.getAccessToken(roleArn, scope);
headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + token);
headers.setContentType(MediaType.APPLICATION_JSON);
return headers;
} catch (Exception ex) {
throw new RuntimeException("Error trying to generate token", ex);
}
}

我使用springboot restTemplate.postForEntity()。我能够击中邮差,并试图编写java代码为相同的。我正在使用post call访问api。对于这个端点令牌和json主体是必需的。我能够生成令牌,下面的请求是通过上面的java代码形成的,但在行号restTemplate.postForEntity()我得到httpclienterroreexception: 400坏请求。我正在记录响应字符串,但由于上述异常,它没有打印。请帮帮我。

JsonBody:{"orderNumber"PO0012345"}

请求格式为:

request is <{"orderNumber":"PO0012345"},{Authorization=[Bearer eyExampleToken], Content-Type=[application/json]}>

请查收附件,附件有邮差请求正文。点击这个链接打开它输入图片描述

设置一个断点:

HttpEntity<String> request = new HttpEntity<>(requestJson.toString(), getHttpHeaders());

检查"requestJson.toString()"。和你通过邮差成功发送的邮件是一样的吗?进行比较。我认为任何人都很难猜测为什么服务器响应400否则。您还可以比较Postman设置的头和Java代码中的头。

最新更新