- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写一个 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/
我一直在开发一个 .NET 字符串格式化库来协助应用程序的本地化。它称为 SmartFormat 并在 GitHub 上开源. 它试图解决的问题之一是 Grammatical Numbers .这也称
leetcode关于单数II的题目是: 给定一个整数数组,除一个元素外,每个元素出现三次。找到那一个。笔记:您的算法应该具有线性运行时复杂度。你能在不使用额外内存的情况下实现它吗? 其实我已经从网站上
我想知道创建/命名模型的首选方法是什么? 我的应用程序有一个“用户”模型,其中包含用于创建、获取、更新(等)用户记录的所有相关业务逻辑。 在我的一些 Controller 中,我可能想要获取多个“用户
在我的 Mysql 数据库中,我有一个术语列表,例如(首字母大写,大多数时候是复数) Hairdressers Restaurants Beauty Salons Fournitures For Re
如果我决定为我的所有路线名称使用复数形式,但某些资源仅作为一个东西存在,您是否将其保持为单数(更直观)或尊重使用复数的决定并保持这种方式? 我们正在用 PHP 为我们的客户门户网站设计一个新的 API
我可能在做一些愚蠢的事情,但是...... 应用/模型/user.rb: class User 然后,当我导航到 /users/123/totem/new 时,出现错误: ActionView::
您能否澄清一些 Matplotlib 术语: “subplots”(或“subplot”?)这个词是“axes”的同义词吗? “轴”和“轴”的单数/复数是什么? 最佳答案 这确实是一个令人困惑的问题。
我有一个 profile我的应用程序中的模型。我想允许用户通过 /profile 查看他们自己的个人资料,所以我创建了这条路线: resource :profile, :only => :show 我
我是一名优秀的程序员,十分优秀!