我在将 DataHandler 与 jax-ws 一起使用时遇到问题。当客户端调用DataHandler的getName()方法时,返回一个空字符串。 在服务器端,它的值是正确的。 这里我汇报一下服务器端和客户端的部分代码:
服务器端
public @XmlMimeType("application/octet-stream") DataHandler fileDownload(String name) {
try {
File file = new File("/tmpwk/share/SharedRepository/apps-data/jaxws-large_upload/" + name);
FileDataSource fds = new FileDataSource(file);
DataHandler dh = new DataHandler(fds);
// Note: getName(), return a String with file name.
System.out.println("File Name = " + dh.getName() );
System.out.println("Content Type " + dh.getContentType());
System.out.println("quiting from downloadFile...");
return dh;
} catch(Exception e) {
throw new WebServiceException(e);
}
}
客户端
public void download() throws IOException {
System.out.println(">>>>> download <<<<<<");
MTOMFeature feature = new MTOMFeature();
UploadImplService service = new UploadImplService();
UploadImpl proxy = service.getUploadImplPort(feature);
Map<String, Object> ctxt = ((BindingProvider)proxy).getRequestContext();
ctxt.put(JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 8192);
DataHandler dh = proxy.fileDownload("file.bin");
InputStream in = dh.getInputStream();
//Note: getName() return a empty string, why ????
System.out.println("File Name = " + dh.getName());
System.out.println("Content Type = " + dh.getContentType());
File file = new File("/tmp/dfile.bin");
OutputStream out = new FileOutputStream(file);
// Transfer bytes from in to out
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
为什么会发生这种情况?
最佳答案
今天我也遇到了同样的情况。幸运的是,我找到了原因。
如果深入调试源代码,您会发现在 JAX-WS 中,DataHandler 类型化参数或结果将被包装到 MIMEPartStreamingDataHandler 中。
MIMEPartStreamingDataHandler 的数据源是一个名为 StreamingDataSource 的内部类。由DataHandler定义,它的getName方法应该由它的dataSource委托(delegate)。然而,StreamingDataSource的getName方法,只是返回一个空字符串“”。就像:
public String getName() {
return "";
}
您可以在 here 中了解源代码的概述。 .
此问题的一个可能的解决方案是:
- 为您的上传服务方法提供另一个参数来指定其名称。
- 使用 String 属性封装结果。
关于java - 从客户端调用时,jax-ws DataHandler getName() 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12250423/