gpt4 book ai didi

java - 如何使用 Java Spring 像 Postman 表单数据一样 POST image.png

转载 作者:行者123 更新时间:2023-11-30 02:22:49 26 4
gpt4 key购买 nike

我正在编写一个 Java 应用程序,它将内容发布到 WordPress Rest Api。但是,我在使用 Java SpringBoot 以编程方式发布“.png”文件时遇到问题,因为我不知道如何将表单数据正文添加到 HttpEntity<>(body, headers);

我已经使用 Postman -> Body -> form-data ->"file":"myFile.png"完成了此操作查看屏幕截图: headers in Postman here Body in Postman here

我在 Java Spring 中编写了这段代码:

private MediaResponse uploadMedia (File graphicsFile) {
String uploadUrl = baseUrl + mediaUrl;
HttpHeaders headers = getHttpHeader();

headers.add(headerKeyAuthorization, User.getInstance().getUsertoken());
headers.add("Content-Disposition", "attachment;filename=image.png");
headers.add("Content-Type", "image/png");

...

我想过做这样的事情:

Map<String, File> body = new HashMap<>();
parameters.put("file", new File("image.png"));

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

//not interesting in this case
//excecuteMediaRequest(uploadUrl, HttpMethod.POST, requestEntity);

将文件添加到正文。

现在我的问题是:我必须在 header (HttpHeaders)中设置哪些“键”:“值”对,以及如何将文件添加到正文中以实现相同的 POST就像 postman 一样?

我的实际解决方案当然会产生错误:

Exception in thread "main" org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [java.util.HashMap] and content type [image/png]

解决方案:

我已经通过一些解决方法和@Ajit Somans 的帮助让它工作了。这是适用于我的场景的代码。请注意,方法 generateBytArray()executeMediaRequest() 和类 MediaResponse 是自己编写的。

/**
* Uploads media to a rest resource.
*
* @param graphicsFile the media file which should be uploaded
* @return a MediaResponse which has access to resource urls and media information.
*/
private MediaResponse uploadMedia (File graphicsFile) {
String uploadUrl = baseUrl + mediaUrl;
final String filename = graphicsFile.getName();
//create headers for form data
HttpHeaders header = getHttpHeader();
header.set(headerKeyAuthorization, User.getInstance().getUsertoken());
header.set("Content-Disposition", "form-data;");

//produces a byte array resource
ByteArrayResource contentAsResource = new ByteArrayResource(generateBytArray(graphicsFile)){
@Override
public String getFilename(){
return filename;
}
};

MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
formData.add("file", contentAsResource);
//create request entity with header and body
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(formData, header);
//executes request with in custom method.
MediaResponse respondingObject = executeMediaRequest(uploadUrl, HttpMethod.POST, requestEntity);
return respondingObject;
}

正如您所看到的,我们没有设置“Content-Type”选项,而是将“Content-Disposition”设置为“form-数据”而不是“附件”。关键部分是将媒体文件(.png)转换为byte[]。之后,我们生成一个 ByteArrayResource,如this post中提到的那样。 。至少我们只是将字节数组设置到正文中并对给定的 url 端点执行请求。

这里是将文件转换为字节[]的方法:

 /**
* generates a byte Array of a file.
*
* @param file the file to generate a byte array of.
* @return byte array of the given file.
*/
private byte[] generateBytArray(File file) {
byte[] res = new byte[0];
try {
//File file = fileResource.getFile();
BufferedImage image = ImageIO.read(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
res = baos.toByteArray();

} catch (IOException e) {
e.printStackTrace();
}

return res;
}

执行方法:

    /**
* Method to execute a Request to a Rest Api where we want to upload media to.
*
* @param url the url endpoint of the resource, where we upload the media file.
* @param method the http request method, which ist POST in this case.
* @param entity the http entity where header and body are stored.
* @return a MediaResponse which has access to resource urls and media information.
*/
private MediaResponse executeMediaRequest(String url, HttpMethod method, HttpEntity entity) {
ParameterizedTypeReference<MediaResponse> responseType = new ParameterizedTypeReference<MediaResponse>() {};
ResponseEntity<MediaResponse> response = template.exchange(url, method, entity,
responseType, MediaResponse.class);

MediaResponse responseObject = response.getBody();
logger.info("\n ******** POST MEDIA from response with param: \n " +
"Post id: '{}' \n " +
"Post REST resource endpoint: '{}' \n" +
"Post Permalink '{}'\n *********",
responseObject.getMediaID(), responseObject.getRestSelfUrl(), responseObject.getPermalink());

return responseObject;
}

谢谢@Ajit Soman

最佳答案

使用LinkedMultiValueMap而不是Map也使用FileSystemResource而不是File。您的文件上传代码可能如下所示:

    LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("file", new FileSystemResource("FILE_LOCATION"));
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "image/png");
.. other headers...
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<LinkedMultiValueMap<String, Object>>(
map, headers);
RestTemplate template = new RestTemplate();
String result = template.postForObject("FILE_UPLOAD_URL",requestEntity, String.class);
System.out.println(result);
return result;

关于java - 如何使用 Java Spring 像 Postman 表单数据一样 POST image.png,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46380712/

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