如何使用Java Spring POST image.png,如Postman form-data

时间:2017-09-23 14:37:08

标签: java wordpress spring rest spring-boot

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

我使用Postman完成了这项工作 - >身体 - > 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);

将文件添加到正文中。

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

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

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 [] 。之后我们生成了this post中提到的ByteArrayResource。至少我们只是将字节数组设置到正文中并执行对给定url端点的请求。

此处将文件转换为 byte [] 的方法:

 /**
 * 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

1 个答案:

答案 0 :(得分:1)

使用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;