简体   繁体   English

将 RestTemplate 用于 Rest API 时出现 400 错误代码

[英]400 Error Code while using RestTemplate for a Rest API

I have a REST API to call and I have written the client using rest template.我有一个 REST API 要调用,我已经使用 rest 模板编写了客户端。 When executing, I am getting 400 status code.执行时,我得到 400 状态码。 The same REST API is working fine when using POSTMAN.使用 POSTMAN 时,相同的 REST API 工作正常。 Below are the code snippets for API and caller.下面是 API 和调用者的代码片段。 Do let me know if anyone catches anything.如果有人抓到任何东西,请告诉我。

REST API for POST method- REST API 用于POST方法-

@ApiOperation(value = "Download repository as zip")
    @ApiResponses({@ApiResponse(code = 200, message = ""), @ApiResponse(code = 400, message = "")})
    @PostMapping(value = "/download", produces = {MediaType.APPLICATION_OCTET_STREAM_VALUE})
    public ResponseEntity<StreamingResponseBody> downloadRepository(
            @RequestBody @Validated final RepositoriesRequest repositoriesRequest) {

        final Situation situation = this.situationsService.getSituationId(repositoriesRequest);
        if (isNull(situation)) {
            return ResponseEntity.notFound().build();
        } else {
            final ExtractionRequest extractionRequest = new ExtractionRequest(repositoriesRequest.getType(), situation,
                    repositoriesRequest.getDatabase());

            if (!this.validateRequest(extractionRequest)) {
                return ResponseEntity.badRequest().build();
            }
            final ExtractionResponse response = this.extractService.extractRepository(extractionRequest);

            if (null == response) {
                return ResponseEntity.notFound().build();
            }
            final InputStream inputStream = this.extractService.getFileFromS3(response.getRepositoryPath());

            if (null == inputStream) {
                return ResponseEntity.noContent().build();
            }

            final StreamingResponseBody bodyWriter = this.bodyWriter(inputStream);

            return ResponseEntity.ok()
                    .header("Content-Type", "application/zip")
                    .header(CONTENT_DISPOSITION, "attachment; filename=\"repository-" + situation.getId() + ".zip\"")
                    .body(bodyWriter);
        }
    }

REST CLIENT using Rest Template with auth token and request body as input - REST CLIENT 使用 Rest 模板,以身份验证令牌和请求正文作为输入 -

HttpEntity<MultiValueMap<String, Object>> buildLoadRepoRequest(
            final SimulationContext context,
            final List<String> tablesName,
            final String simulationId,
            final Integer offset) {
        final Token token = this.authenticateOkoye(simulationId, offset);
        LOGGER.info("Token Run: {}", token.getAccessToken());
        final String database = this.getDatabaseForEnvironment();

        final HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(APPLICATION_JSON_UTF8);
        httpHeaders.set(AUTHORIZATION, "Bearer " + token.getAccessToken());

        final MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("database", database);
        body.add("monthlyClosingMonth", context.getMonthlyClosingDate());
        body.add("repositorySnapshot", context.getRepository());
        body.add("situationId", context.getSituationId());
        body.add("tableNames", tablesName);
        body.add("type", context.getRunType());

        return new HttpEntity<>(body, httpHeaders);
    }

Exception Handler -异常处理程序 -

    @Override
    @ExceptionHandler(HttpClientErrorException.class)
    public void loadRepository(
            final SimulationContext context,
            final List<String> tablesName,
            final String simulationId,
            final Integer offset,
            final Path repositoryPath) throws IOException {
        LOGGER.info("[{}] [{}] repository tablesName: {}", simulationId, offset, tablesName);
        this.restTemplate.setRequestFactory(this.getClientHttpRequestFactory());
        final ClientHttpResponse response = this.restTemplate.postForObject(
                this.repositoriesUrl,
                this.buildLoadRepoRequest(context, tablesName, simulationId, offset),
                ClientHttpResponse.class);

        if (response != null && HttpStatus.OK == response.getStatusCode()) {
            LOGGER.info(
                    "response status on simulation : {}  - Context: {} - status: {}",
                    simulationId,
                    offset,
                    response.getStatusCode());
            //this.helper.copy(response.getBody(), repositoryPath);
        } else if (response != null && HttpStatus.NO_CONTENT != response.getStatusCode()) {
            throw new JarvisException(
                    "Can't retrieve RWA repository on simulation " + simulationId + " Context:" + offset);
        }
    }

We have been looking into this issue since yesterday and still don't have any clue.从昨天开始,我们一直在研究这个问题,但仍然没有任何线索。 So far we have tried postForEntity, exchange, changing the headers to proper setter methods and tried passing the parameters as an object also.到目前为止,我们已经尝试过 postForEntity、交换、将标头更改为适当的设置方法,并尝试将参数作为 object 也传递。 None of them worked.他们都没有工作。

I have a strong feeling about something being wrong at header level while calling the API.在调用 API 时,我强烈感觉 header 级别出现问题。

Did you try to use httpHeaders.setContentType(MediaType.APPLICATION_JSON)您是否尝试使用httpHeaders.setContentType(MediaType.APPLICATION_JSON)

Or add consumes to @PostMapping annotation with APPLICATION_JSON_UTF8 value或者使用 APPLICATION_JSON_UTF8 值将消耗添加到 @PostMapping 注释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM