我只想知道,有没有解析MTOM/XOP SOAP响应的简单方法。问题是,我使用纯HTTP发送soap消息,并使用javax.xml解析响应。但是有些服务用mulipart/related来响应我,并且需要更复杂的逻辑来解析它(性能很重要)。所以我想知道我是否可以以某种方式利用apachecxf、apacheaxiom或任何其他库来解析MTOM/XOP SOAP响应?
这些单元测试向您展示了如何使用CXF从MTOM消息中提取附件。我将内联其中一个测试,以防将来不存在此链接:
private MessageImpl msg;
@Before
public void setUp() throws Exception {
msg = new MessageImpl();
Exchange exchange = new ExchangeImpl();
msg.setExchange(exchange);
}
@Test
public void testDeserializerMtom() throws Exception {
InputStream is = getClass().getResourceAsStream("mimedata");
String ct = "multipart/related; type="application/xop+xml"; "
+ "start="<soap.xml@xfire.codehaus.org>"; "
+ "start-info="text/xml; charset=utf-8"; "
+ "boundary="----=_Part_4_701508.1145579811786"";
msg.put(Message.CONTENT_TYPE, ct);
msg.setContent(InputStream.class, is);
AttachmentDeserializer deserializer = new AttachmentDeserializer(msg);
deserializer.initializeAttachments();
InputStream attBody = msg.getContent(InputStream.class);
assertTrue(attBody != is);
assertTrue(attBody instanceof DelegatingInputStream);
Collection<Attachment> atts = msg.getAttachments();
assertNotNull(atts);
Iterator<Attachment> itr = atts.iterator();
assertTrue(itr.hasNext());
Attachment a = itr.next();
assertNotNull(a);
InputStream attIs = a.getDataHandler().getInputStream();
// check the cached output stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(attBody, out);
assertTrue(out.toString().startsWith("<env:Envelope"));
// try streaming a character off the wire
assertTrue(attIs.read() == '/');
assertTrue(attIs.read() == '9');
}
在您的情况下,ct
将来自响应的内容类型标头。"mimedata"
将是响应的内容。
无需使用CXF,标准的javax.mail.internet.MimeMultipart类可以完成这项工作,而且非常容易使用(也可以创建MTOM请求)。
这里有一个非常简单的例子来解码MTOM响应的部分:
MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(data, contentType));
int count = mp.getCount();
for (int i = 0; i < count; i++) {
BodyPart bp = mp.getBodyPart(i);
bp.saveFile(filepath + "_" + i);
}
我遇到了与@Nicolas Albert 相同的问题并得到了解决
public byte[] mimeParser(InputStream isMtm) {
ByteArrayOutputStream baos = null;
try {
MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(isMtm,
ct));
int count = mp.getCount();
baos = new ByteArrayOutputStream();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = mp.getBodyPart(i);
if (!Part.ATTACHMENT
.equalsIgnoreCase(bodyPart.getDisposition())
&& !StringUtils.isNotBlank(bodyPart.getFileName())) {
continue; // dealing with attachments only
}
bodyPart.writeTo(baos);
}
byte[] attachment = baos.toByteArray();
FileUtils.writeByteArrayToFile(new File("E:/wss/attachment.zip"), attachment);
return attachment;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (baos != null) {
try {
baos.close();
} catch (Exception ex) {
}
}
}
return null;
}