问题描述
我注意到这里的多部分请求有一个奇怪的问题。
以下是 Spring Boot 2.4.2 中使用的 Jersey2 实现:
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
public void upload(@FormDataParam("params") MyPojo req,@FormDataParam("file") FormDataBodyPart file,@Context HttpHeaders headers,@Suspended AsyncResponse ar)
{
...
}
并遵循 Spring Boot 依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
我能够使用 Postman 成功上传 JSON 和文件(作为多部分/表单数据),但来自 Java 客户端的相同请求引发以下错误:
Caused by: org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
SO 上的这个 article 说我们需要添加一个 CommonsMultipartResolver
但为什么它在 Postman 客户端上运行良好??
感谢任何提示或建议,谢谢。
更新 Java Apache 客户端代码:
final Document document = getDocument(documentId);
final String requestParams = getRequestParams(document);
final String documentContentType = document.getContentType();
final URL endpoint = getServiceEndpoint();
final multipartentityBuilder entityBuilder = multipartentityBuilder.create().addTextBody(REQUEST_ParaMS_ParaMETER_NAME,requestParams,ContentType.APPLICATION_JSON);
if (isSendDocument() && documentFile != null) {
entityBuilder.addBinaryBody(DOCUMENT_CONTENT_ParaMETER_NAME,documentFile,ContentType.parse(documentContentType),document.getContentType());
}
final httpentity reqestEntity = entityBuilder.build();
connection = (HttpURLConnection)endpoint.openConnection();
connection.setAllowUserInteraction(false);
connection.setConnectTimeout(getConnectionTimeout());
connection.setReadTimeout(getReadTimeout());
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.addRequestProperty(X_REQUESTED_WITH_HEADER_NAME,"XMLHttpRequest");
connection.addRequestProperty(X_REQUESTED_BY_HEADER_NAME,"XMLHttpRequest");
connection.addRequestProperty(ACCEPT_HEADER_NAME,ContentType.APPLICATION_JSON.getMimeType());
connection.addRequestProperty(CONTENT_TYPE_HEADER_NAME,reqestEntity.getContentType().getValue());
outStream = connection.getoutputStream();
reqestEntity.writeto(outStream);
outStream.flush();
解决方法
由于我们打算由 Jersey servlet 处理多部分,@PaulSamsotha 建议禁用 Spring Boot 的多部分处理 spring.servlet.multipart.enabled = false
解决了问题中发布的原始问题 - “java.lang.IllegalStateException:无法处理部分因为没有提供多部分配置”。
后来,我仅在使用 Apache 客户端时收到 Http 400 错误,这是由于格式错误的 JSON 有效负载。感谢大家的支持。