Java - Resttemplate - 使用multipart / form-data进行POST

时间:2017-08-10 16:14:05

标签: java http-post multipartform-data resttemplate walmart-api

我必须向WALMART API发出POST请求,以便将我的产品上传到他们的平台上。我有一个包含要发送的请求的xml文件。 我的请求适用于ARC / Postman(下面可以看到工作版本的示例),问题是我无法使用Resttemplate在Java中工作,我根本无法正确设置正文请求(实际文件)。

您可以使用Resttemplate帮助将请求从下图转换/转换为Java吗?

到目前为止,我有这个代码来设置上面的标题(出于安全原因硬编码了一些值):

    headers = new HttpHeaders();
    headers.set("WM_SVC.NAME", "Walmart Marketplace");
    headers.set("WM_QOS.CORRELATION_ID", "123456abcdef");
    headers.set("WM_SEC.TIMESTAMP", timestamp);
    headers.set("WM_SEC.AUTH_SIGNATURE", signatureString);
    headers.set("WM_CONSUMER.ID", "my-consumer-id-cut-for-security-reasons");
    headers.set("WM_CONSUMER.CHANNEL.TYPE", "my-channel-type");
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
    headers.set("Host", "https://marketplace.walmartapis.com");

和实际请求:

File file = new File("C:\\walmartfeed.xml");
DiskFileItem fileItem = new DiskFileItem("file", "text/xml", false, file.getName(), (int) file.length(), file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

MultiValueMap<String, Object> parts =
        new LinkedMultiValueMap<String, Object>();
parts.add("file", new ByteArrayResource(multipartFile.getBytes()));

HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(parts, headers);
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
restTemplate.getMessageConverters().add(new MultipartAwareFormHttpMessageConverter());

ResponseEntity<FeedAcknowledgement> response = restTemplate.exchange("https://marketplace.walmartapis.com/v3/feeds?feedType=item", org.springframework.http.HttpMethod.POST, request, FeedAcknowledgement.class);

谢谢

this is the link for the image

0 个答案:

没有答案