有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java RestTemplate:如何发送多部分?

我需要发送请求。看起来是这样的卷曲请求:

 curl --location --request POST 'http://127.0.0.1:8080/api/attachments'
--form 'data=@path/to/file/6C233C5F-B60D-41CA-86ED-A43C51FD7EED.png'

如果要将其转换为IDEA http请求,应如下所示:

POST http://127.0.0.1:8080/api/attachments
Content-Type: multipart/form-data; boundary=WebAppBoundary

--WebAppBoundary
Content-Disposition: form-data; name="data"; filename="6C233C5F-B60D-41CA-86ED-A43C51FD7EED.png"

< path/to/file/6C233C5F-B60D-41CA-86ED-A43C51FD7EED.png
--WebAppBoundary--

好的,但我需要把它和restTemplate一起寄出去。最好使用byte[]而不是文件路径。 请帮帮我


共 (1) 个答案

  1. # 1 楼答案

    这是我的代码片段

            HttpEntity<?> entity;
            HttpHeaders headers = new HttpHeaders();
            Object requestBody;
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            requestBody = Base64.getDecoder().decode(base64EncodedData);
    
            entity = new HttpEntity<>(requestBody, headers);
    
            ResponseEntity response = getRestTemplate().exchange(
                    serviceURL,
                    HttpMethod.POST,
                    entity,
                    String.class
            );
    

    您可以将文件内容读取到字节数组,并以相同的方式发送