首页 > 解决方案 > 如何使用 spring RestTemplate 生成带有二进制数据的 curl 请求?

问题描述

我有以下请求在 curl 中正常工作,一切正常。我需要通过使用 spring 和 RestTemplate 来做到这一点。

curl 'http://myweb.web.com/upload/temp/myImage.jpg' -X PUT  -H 'Origin:  http://myweb.web.com' -H 'Connection: keep-alive' -H 'Referer: http://myweb.web.com/new'  --data-binary @/opt/myImage.jpg 

标签: javaspringrestspring-bootresttemplate

解决方案


你可以这样做:

public void uploadFileTemplate() throws IOException {
        MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
        bodyMap.add("user-file", getUserFileResource());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyMap, headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/upload",
                HttpMethod.POST, requestEntity, String.class);
        System.out.println("response status: " + response.getStatusCode());
        System.out.println("response body: " + response.getBody());
    }

    public static Resource getUserFileResource() throws IOException {
        //todo replace tempFile with a real file
        Path tempFile = <path-to-your-imagefile>
        System.out.println("uploading: " + tempFile);
        File file = tempFile.toFile();
        return new FileSystemResource(file);
    }

推荐阅读