gpt4 book ai didi

java - 为什么我无法使用 RestTemplate 将文件发送或 POST 到服务器?

转载 作者:行者123 更新时间:2023-12-01 16:59:28 28 4
gpt4 key购买 nike

    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,必须以 Multipart-Form-data 形式发送。

我在 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();
}
}
}

关于java - 为什么我无法使用 RestTemplate 将文件发送或 POST 到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61532633/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com