Spring 启动 RestTemplate - multipart/mixed

Spring boot RestTemplate - multipart/mixed

有一个 REST API 只接受内容类型 multipart/mixed。

正在尝试使用 restTemplate 并生成内容类型为 multipart/mixed 的 REST 请求。 如果我评论 setContentType restTemplate 默认为 multipart/form-data.

setContentType(MediaType.parseMediaType("multipart/mixed"))

但是运气不好,有什么例子可以调用 API 生成 multipart/mixed 请求吗?

也许这有帮助

HttpHeaders publishHeaders = new HttpHeaders();
publishHeaders.set(HEADER_TABLEAU_AUTH, token);
publishHeaders.setContentType(MediaType.parseMediaType("multipart/mixed"));
String response;
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
String payload = "<tsRequest>\n" +
        ............................
       "</tsRequest>";
map.add(TABLEAU_PAYLOAD_NAME, payload);
map.add("tableau_datasource", new FileSystemResource("/extract/test.tde"));
HttpEntity<LinkedMultiValueMap<String, Object>> entity = new HttpEntity<>(map, publishHeaders);
try {
response = restTemplate.postForObject(url + PUBLISH_DATASOURCE_SINGLE_CHUNK, entity, String.class, siteId);
} catch (RestClientException restEx) {
   log.error(....);
   throw restEx;
}

因此,不幸的是,"spring-web-4.3.12.RELEASE.jar" 中的 Springs RestTemplate 的当前实现确实无法解决您的问题。它假定在​​所有情况下,唯一的多部分数据类型是“multipart/form-data:,因此它不会识别您请求的多部分性质。

org.springframework.http.converter.FormHttpMessageConverter:第 247-272 行

@Override
@SuppressWarnings("unchecked")
public void write(MultiValueMap<String, ?> map, MediaType contentType, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {

    if (!isMultipart(map, contentType)) {
        writeForm((MultiValueMap<String, String>) map, contentType, outputMessage);
    }
    else {
        writeMultipart((MultiValueMap<String, Object>) map, outputMessage);
    }
}


private boolean isMultipart(MultiValueMap<String, ?> map, MediaType contentType) {
    if (contentType != null) {
        return MediaType.MULTIPART_FORM_DATA.includes(contentType);
    }
    for (String name : map.keySet()) {
        for (Object value : map.get(name)) {
            if (value != null && !(value instanceof String)) {
                return true;
            }
        }
    }
    return false;
}

如果您查看私有方法的第一部分 "isMultipart",您将看到:

    if (contentType != null) {
        return MediaType.MULTIPART_FORM_DATA.includes(contentType);
    }

它会检查您是否已声明 "multipart/form-data",但您的声明是 "multipart/mixed",因此失败。

还有许多其他点也可能会失败,但这是问题的根源。

如果您仍想使用 RestTemplate,唯一的解决方案是实现您自己的可识别所需媒体类型的消息转换器,并将其添加到模板消息转换器中。

您还可以通过扩展、复制粘贴和修改来编写您自己的 RestTemplate 变体,或者从头开始创建一个客户端,使用一些更基本的东西,比如 apaches HttpClient(甚至 CORE java I假设)。