[英]How produce my curl request with binary data by use of spring RestTemplate?
我有以下要求在 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
你可以这样做:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.