当服务器在 Spring Rest 模板中处理请求时,多部分请求从客户端终止

问题描述 投票:0回答:1

我有 2 项服务

service A
service B

  • service A
    => 写成
    spring-boot, java
  • service B
    => 用
    quarkus, java
    书写。

我正在向

service A
发出多部分请求。该请求包含一个

    {
        field1: String,
        field2: MultipartFile //This is an image file
    }

Service A
应该通过对 url
field2
的 POST 请求将第二个字段
service B
转发到
http://localhost:8080/upload
。 当直接 POST 请求发送到 url
Service B
时,
http://localhost:8080/upload
工作正常。所以,我认为
service B
没有任何问题。

Service A
我有,

控制器功能:

@PostMapping
    public String createPost(@ModelAttribute PostDTO post) {
        return postService.create(post);
    }

服务功能:

public String create(PostDTO postDto) {
        String fileName = uploadFiles(postDto.files());
        //other logics
        return "<upload status>";
    }
private String uploadFiles(MultipartFile files) {
        try {
            FileUploadRequestDTO request = new FileUploadRequestDTO(files);
            HttpHeaders headers = new HttpHeaders();
            // MediaType.MULTIPART_FORM_DATA
            headers.setContentType(request.getContentType());
            // calculated as per the received content
            headers.setContentLength(request.getContentLength());
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(request.getBody(), headers);
            ResponseEntity<FileUploadResponse> uploadResponse = rt.postForEntity("http://localhost:8080/upload", requestEntity, FileUploadResponse.class);
            if (uploadResponse.getStatusCode().is2xxSuccessful()) {
                return Objects.requireNonNull(uploadResponse.getBody()).fileName();
            } else {
                throw new FileUploadFailed("Storage Engine returned error response");
            }
        } catch (IOException e) {
            throw new FileUploadFailed("could not retrieve file size of the attached file");
        }
    }

我认为

uploadFiles()
函数存在一些问题,连接被不正确地终止。

来自

service B
我正在收到

IOError processing HTTP request to /upload failed, the client likely terminated the connection. Error id: <some string>: java.io.IOException: Connection terminated parsing multipart request

请提出一些我可以做的改变

java spring-boot multipartform-data quarkus resttemplate
1个回答
0
投票

我认为标题在计算内容长度的方式上存在一些问题:

 headers.setContentLength(request.getContentLength());

一旦我删除此标头,请求就不再终止

© www.soinside.com 2019 - 2024. All rights reserved.