为什么我不能将带有 RestTemplate 的文件发送或发布到服务器?


File fileJson = new File("answer.json");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
**body.add("answer", fileJson);**
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
String urlFinal = "url";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(urlFinal, requestEntity, String.class);
System.out.println(response);

服务器返回一个400错误,说文件没有在正文中发送。我想知道是我的代码出了问题还是服务器出了问题。

该文件是一个JSON,必须以多部分表单数据的形式发送。

作为一个例子,我在urlFinal字符串中只留下了"url",但有一个有效的url,因为我已经做了测试。

您需要将文件名和BAOS添加到MultiValueMap主体,添加如下:

File fileJson = new File("answer.json");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("filename", fileJson.getName());
body.add("file", new ByteArrayResource(Files.readAllBytes(fileJson.toPath()));
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
String urlFinal = "url";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity(urlFinal, requestEntity, String.class);
System.out.println(response);

但不是最好的模式,因为你可以更改你的代码使用这种方法:

@Service
public class FileUploadService {
private RestTemplate restTemplate;
@Autowired
public FileUploadService(RestTemplateBuilder builder) {
this.restTemplate = builder.build();
}
public void postFile(String filename, byte[] someByteArray) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// This nested HttpEntiy is important to create the correct
// Content-Disposition entry with metadata "name" and "filename"
MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
ContentDisposition contentDisposition = ContentDisposition
.builder("form-data")
.name("file")
.filename(filename)
.build();
fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());
HttpEntity<byte[]> fileEntity = new HttpEntity<>(someByteArray, fileMap);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", fileEntity);
HttpEntity<MultiValueMap<String, Object>> requestEntity =
new HttpEntity<>(body, headers);
try {
ResponseEntity<String> response = restTemplate.exchange(
"/urlToPostTo",
HttpMethod.POST,
requestEntity,
String.class);
} catch (HttpClientErrorException e) {
e.printStackTrace();
}
}
}

最新更新