要在骆驼中处理多部分,您可以使用unmarshal().mimeMultipart()。在这一行之后,Camel Exchange 包含一个AttachmentMessage,它的主体是多部分的第一部分。接下来的部分可以通过在 Camel 处理器中调用attachmentMessage.getAttachmentObjects() 来获得。有关unmarshal().mimeMultipart() 工作原理的更多信息,请参阅org.apache.camel.dataformat.mime.multipart.MimeMultipartDataFormat 中方法unmarshall() 的源代码。
进一步的行动取决于您的情况。例如,如果 multipart 的第一部分始终包含您的 SimplePojo 类的 json 对象,那么您可以在 unmarshal().mimeMultipart() 之后立即使用 unmarshal().json(SimplePojo.class)。然后骆驼身体将包含您的pojo。下一部分的DataHandlers可以通过以下方式获取:
DataHandler dataHandler = attachmentObjects.get("test.txt").getDataHandler();
// test.txt comes from the filename field of the Content-Disposition header in case you have multipart/form-data.
以下是处理来自位于 {{http.url}} 的 REST 服务的响应的示例,采用以下形式的多部分格式:
--Boundary_2411_1961957611_1491990591774
Content-Disposition: form-data; name="part1"
Content-Type: application/json; charset=utf-8
{
"id": 123,
"name": "simple pojo"
}
--Boundary_2411_1961957611_1491990591774
Content-Disposition: form-data; name="part2"; filename="test.txt"
Content-Type: application/octet-stream
test
--Boundary_2411_1961957611_1491990591774--
骆驼路线构建器:
from("direct:start")
.setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.GET))
.to("{{http.url}}")
.unmarshal().mimeMultipart()
.unmarshal().json(SimplePojo.class)
.process(exchange -> {
AttachmentMessage attachmentMessage = exchange.getMessage(AttachmentMessage.class);
SimplePojo simplePojo = attachmentMessage.getBody(SimplePojo.class);
Map<String, Attachment> attachmentObjects = attachmentMessage.getAttachmentObjects();
DataHandler dataHandler = attachmentObjects.get("test.txt").getDataHandler();
})
.to("mock:end");
SimplePojo:
public class SimplePojo {
private Long id;
private String name;
//...
//getters, setters
}
为了使unmarshal().mimeMultipart() 和unmarshal().json(SimplePojo.class) 工作,您必须具有依赖项:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-mail</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jackson</artifactId>
<version>${camel.version}</version>
</dependency>