当前位置: 首页 > 知识库问答 >
问题:

获取异常组织。springframework。网状物客户HttpClientErrorException:400使用restTemplate时请求错误。后期实体

陆英毅
2023-03-14
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()。我能够完成postman并尝试为其编写java代码。我正在使用post调用访问api。对于该endpoint令牌和以下json体是必需的。我能够生成令牌,下面的请求是通过上面的java代码生成的,但行号是restTemplate。postForEntity()我收到HttpClientErrorException:400个错误请求。我正在记录响应字符串,但由于上述异常,它没有打印。请帮帮我。

JsonBody:{"orderNumber":"PO0012345"}

形成的请求是:

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

请查找包含邮递员请求正文的附件。单击此链接将其打开,在此处输入图像描述

共有1个答案

羊舌兴德
2023-03-14

在此行上放置断点:

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

检查值requestJson。toString()。它和你成功寄来的邮递员的信一样吗?比较它们。我认为任何人都很难猜测为什么服务器会以400作为响应。您还可以在Java代码中比较Postman设置的标题与您的标题。

 类似资料: