如何为text/xml
创建mime-atachment SOAPMessage
?
我有一个函数,它发送XML的二进制文件。但我不知道我该怎么做。
答案 0 :(得分:0)
使用DataHandler / DataSource将二进制数据推送到客户端的消息中。
在服务器端,您需要创建一个DataContentHandler实现并将其注册到激活框架。
第1步 - 添加二进制附件
实现一个简单的DataSource来获取数据:
import javax.activation.*;
class BinaryDataSource implements DataSource {
InputStream _is;
public BinaryDataSource(InputStream is) {
_is = is;
}
public String getContentType() { return "application/binary"; }
public InputStream getInputStream() throws IOException { return _is; }
public String getName() { return "some file"; }
public OutputStream getOutputStream() throws IOException {
throw new IOException("Cannot write to this file");
}
}
现在使用此代码添加附件:
InputStream data = ...
SOAPMessage msg = ...
DataHandler dh = new DataHandler(new BinaryDataSource(data));
AttachmentPart attachment = msg.createAttachmentPart(dh);
msg.addAttachmentPart(attachment);
第2步 - 设置服务器端
[注意:这对我有用]
创建一个DataContentHandler来处理类型" application / binary"的传入附件。
import javax.activation.*;
import java.io.*;
public class BinaryDataHandler implements DataContentHandler {
/** Creates a new instance of BinaryDataHandler */
public BinaryDataHandler() {
}
/** This is the key, it just returns the data uninterpreted. */
public Object getContent(javax.activation.DataSource dataSource) throws java.io.IOException {
System.out.println("BinaryDataHandler: getContent called with: " + dataSource);
return dataSource.getInputStream();
}
public Object getTransferData(java.awt.datatransfer.DataFlavor dataFlavor,
javax.activation.DataSource dataSource)
throws java.awt.datatransfer.UnsupportedFlavorException,
java.io.IOException {
return null;
}
public java.awt.datatransfer.DataFlavor[] getTransferDataFlavors() {
return new java.awt.datatransfer.DataFlavor[0];
}
public void writeTo(Object obj, String str, java.io.OutputStream outputStream)
throws java.io.IOException {
// You would need to implement this to have
// the conversion done automatically based on
// mime type on the client side.
}
}
现在,您可以使用此代码获取附件的数据:
SOAPMessage msg = ... //received message
Iterator ats = msg.getAttachments();
if( ats.hasNext() ){
AttachmentPart attachment = (AttachmentPart)ats.next();
InputStream contents = (InputStream)attachment.getContent();
}
最后,您需要注册DataContentHandler,以便激活框架将使用它。有两种方法(请参阅激活框架javadocs中的MailcapCommandMap)。我做的是创建一个名为" mailcap"在我的" java"使用的lib目录中解释
此文件如下所示:
应用/二进制; BinaryDataHandler 应用/二进制;;的x java的内容处理器= BinaryDataHandler
这告诉激活框架使用您的处理程序来指示 MIME类型。