我想在其余模板中连同Json请求一起上传文件以及其他属性。但是我做不到。

@Bean
public RestTemplate getRestTemplate(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.build();
}

@Autowired
private RestTemplate restTemplate;

@Scheduled(fixedDelay = 1000)
public void _do() throws Exception {
    HashMap<String, String> documentProperties = new HashMap<>();
    documentProperties.put("number", "123");


    MultipartFile file = Somefile;


    UploadDocumentRequest uploadDocumentRequest = new UploadDocumentRequest();
    uploadDocumentRequest.setDocumentClass("DocClass");
    uploadDocumentRequest.setDocumentProperties(documentProperties);
    uploadDocumentRequest.setFile(file);  ----???





    ResponseEntity<String> value = restTemplate.postForEntity("URL", uploadDocumentRequest, String.class);

    }

最佳答案

您必须使用标题和正文创建HttpEntity


将内容类型标头值设置为MediaType.MULTIPART_FORM_DATA。
将请求正文构建为LinkedMultiValueMap类的实例。
构造一个包装标题和正文对象的HttpEntity实例,并使用RestTemplate将其发布。


示例代码如下所示:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", getFileToBeUploaded());

HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(serviveUrl, requestEntity, String.class);

关于java - 具有文件和其他属性的postForEntity的其余模板,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58002097/

10-13 03:27