清单 3. 使用 SAAJ
| 以下是引用片段: public File resize(String endPoint,File file) { SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection(); SOAPMessage message = MessageFactory.newInstance().createMessage(); SOAPPart part = message.getSOAPPart(); SOAPEnvelope envelope = part.getEnvelope(); SOAPBody body = envelope.getBody(); SOAPBodyElement operation = body.addBodyElement( envelope.createName("resize", "ps", "http://psol.com/2004/ws/resize")); operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/"); DataHandler dh = new DataHandler(new FileDataSource(file)); AttachmentPart attachment = message.createAttachmentPart(dh); SOAPElement source = operation.addChildElement("source",""), percent = operation.addChildElement("percent",""); message.addAttachmentPart(attachment); source.addAttribute(envelope.createName("href"), "cid:" + attachment.getContentId()); width.addTextNode("20"); SOAPMessage result = connection.call(message,endPoint); part = result.getSOAPPart(); envelope = part.getEnvelope(); body = envelope.getBody(); if(!body.hasFault()) { Iterator iterator = result.getAttachments(); if(iterator.hasNext()) { dh = ((AttachmentPart)iterator.next()).getDataHandler(); String fname = dh.getName(); if(null != fname) return new File(fname); } } return null; } |
谈到效率,看一看清单 4,这是 清单 3 更常见的 JAX-RPC 版本(也短得多)。JAX-RPC 预处理程序生成一个存根程序,极大简化了编码。您把 DataHandler 对象作为参数传递,JAX-RPC 自动生成附件。
清单 4. 更有效的 JAX-RPC
| 以下是引用片段: public File resize(File file) throws ServiceException, RemoteException { AttachmentService service = new AttachmentServiceLocator(); AttachmentTip port = service.getAttachmentTip(); // get stub DataHandler dh = new DataHandler(new FileDataSource(file)); DataHandler result = port.resize(dh,20); return new File(result.getName()); } |
选择是一件好事,而 SOAP 为您处理二进制数据提供了选择:您可以在 XML有效负载中使用 base 64编码――对于小的数据集这种方法很好,也可以向请求中附加大的没有编码的二进制文件。
原文链接:http://www.cnblogs.com/xqzhao/archive/2008/03/31/1130610.html
关注此文的读者还看过: