SAAJ访问javawebService实现文件上传

来源:互联网 发布:有没有人能告诉你 知乎 编辑:程序博客网 时间:2024/06/08 07:25


-----以下内容摘自百度百科

SAAJ(SOAP withAttachments API for JAVA)

SAAJ是在松散耦合软件系统中利用SOAP协议实现的基于XML消息传递的API规范。顾名思义,SAAJ支持带附件的SOAP消息。

对于Java API for XML Messaging (JAXM),您已经了解很多,并且可能感到奇怪,究竟JAXM发生了什么事?JAXM 1.0的理念是通过提供消息传递和SOAP API,允许开发人员根据SOAP编写支持消息传递标准的业务应用程序。随着JAXM 1.1版的推出,SOAP API(javax.xml.soap)被分割成了SAAJ1.1规范和JAXM1.1JAXM1.1只包含基于消息传递的APIjavax.xml.messaging)。目前,正在使用的SAAJ版本是1.2WebLogic Server8.1 SP2 支持SAAJ 1.1规范。

SAAJ 1.2 API主要由javax.xml.soap包组成,它为带有多用途互连网邮件扩展协议(MIME)附件的SOAP消息提供抽象。该API提供了创建到端点的点到点连接的方法、创建并处理SOAP消息和附件的方法,以及接收和处理SOAP错误的方法。

虽然在开发企业应用程序的时候,有几种技术供您选择,但对于不同的问题,某些技术可能更合适。选择正确的工具非常重要。

选择SAAJ的理由是什么呢?SAAJ无疑很适合基于文档的同步或者异步Web ServiceSAAJ使用简单,有助于您在Java环境中集成各种Web Service,它扩展了对文档风格的Web Service通信的自然支持(natural support)。SAAJ还支持基于标准接口上的XML消息传递,并且这一点得到了供应商的广泛支持。


http://docs.oracle.com/javaee/5/tutorial/doc/bnbhg.html



编写服务接口:

package com.bs.service;import javax.activation.DataHandler;import javax.jws.WebParam;import javax.jws.WebService;import javax.xml.bind.annotation.XmlMimeType;@WebServicepublic interface ITestService {public void test(@WebParam(name="content")String test);public String sayHello(@WebParam(name="name")String name);// 上传二进制文件    public boolean upload(String fileName, @XmlMimeType("application/octet-stream") DataHandler handler);    //下载二进制文件    public @XmlMimeType("application/octet-stream")DataHandler download(String fileName);}
编写服务实现类:
package com.bs.service.impl;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.jws.WebService;import javax.xml.bind.annotation.XmlMimeType;import javax.xml.ws.WebServiceException;import com.bs.service.ITestService;@WebService(endpointInterface="com.bs.service.ITestService")public class TestService implements ITestService {@Overridepublic void test(String test) {System.out.println(test);}@Overridepublic String sayHello(String name) {return "hello:" + name;}private final File saveDir = new File("d:/share/server");@Overridepublic boolean upload(String fileName, @XmlMimeType(value="application/octet-stream")DataHandler handler){ try {            handler.writeTo(new FileOutputStream(new File(saveDir, fileName)));            return true;        } catch (FileNotFoundException e) {            throw new WebServiceException("Fail to upload.",e);        } catch (IOException e) {            throw new WebServiceException("Fail to upload.",e);        }}@Overridepublic @XmlMimeType("application/octet-stream")DataHandler download(String fileName){return new DataHandler(new FileDataSource(new File(saveDir,fileName)));}}
发布web服务,这里使用cxf框架发布服务
<import resource="classpath:META-INF/cxf/cxf.xml" /><import resource="classpath:META-INF/cxf/cxf-servlet.xml" /><jaxws:endpoint   id="testWebservice"   implementor="com.bs.service.impl.TestService"   address="/testWebservice"/>

新建另外一个java普通项目,进行测试

package com.bs.test.junit;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.net.MalformedURLException;import java.net.URL;import java.util.UUID;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.xml.namespace.QName;import javax.xml.soap.AttachmentPart;import javax.xml.soap.MessageFactory;import javax.xml.soap.MimeHeaders;import javax.xml.soap.SOAPBody;import javax.xml.soap.SOAPBodyElement;import javax.xml.soap.SOAPConnection;import javax.xml.soap.SOAPConnectionFactory;import javax.xml.soap.SOAPElement;import javax.xml.soap.SOAPEnvelope;import javax.xml.soap.SOAPFactory;import javax.xml.soap.SOAPHeader;import javax.xml.soap.SOAPMessage;import javax.xml.soap.SOAPPart;import javax.xml.ws.Dispatch;import javax.xml.ws.soap.SOAPBinding;import org.apache.cxf.interceptor.LoggingInInterceptor;import org.apache.cxf.interceptor.LoggingOutInterceptor;import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;import com.bs.service.ITestService;public class TestWebService {/** * @param args * @throws Exception  */public static void main(String[] args) throws Exception {test();}    //上传附件所在文件夹final static File uploadDir = new File("d:/share/client/upload");public static void testSAAJ()throws Exception{String endpointAddress = "http://localhost:8080/ssh_book/services/testWebservice?wsdl";URL wsdlUrl = new URL(endpointAddress);String ns = "http://impl.service.bs.com/";QName serverName = new QName(ns,"TestServiceService");javax.xml.ws.Service  service = javax.xml.ws.Service.create(wsdlUrl,serverName);String portName = "TestServicePort"; QName portQName = new QName(ns, portName); Dispatch<SOAPMessage> dispatch = service.createDispatch(portQName, SOAPMessage.class, javax.xml.ws.Service.Mode.MESSAGE);SOAPMessage soapMsg = MessageFactory.newInstance().createMessage();SOAPPart soapPart = soapMsg.getSOAPPart();          SOAPEnvelope env = soapPart.getEnvelope();          SOAPBody body = env.getBody();        String iNs = "http://service.bs.com/";        /*SOAPFactory soapFactory = SOAPFactory.newInstance();        Name bodyName = soapFactory.createName("sayHello", "tn", iNs);        QName name = new QName(iNs,"sayHello","tn");        SOAPBodyElement element = body.addBodyElement(name);        element.addChildElement("name").setTextContent("sdfsf");*/                QName name = new QName(iNs,"test","tn");        SOAPBodyElement element = body.addBodyElement(name);        element.addChildElement( new QName("content")).setTextContent("sdfsf");                soapMsg.writeTo(System.out);          System.out.println();          System.out.println("---invoke-----");          SOAPMessage response = dispatch.invoke(soapMsg);        response.writeTo(System.out);}//访问服务中的test方法public static void testSAAJ2() throws Exception{String endpointAddress = "http://localhost:8080/ssh_book/services/testWebservice";URL wsdlUrl = new URL(endpointAddress);SOAPConnectionFactory soapConnectionFactory =                SOAPConnectionFactory.newInstance();            SOAPConnection connection =                soapConnectionFactory.createConnection();            SOAPMessage soapMsg = MessageFactory.newInstance().createMessage();    SOAPPart soapPart = soapMsg.getSOAPPart();              SOAPEnvelope env = soapPart.getEnvelope();              SOAPBody body = env.getBody();            String iNs = "http://service.bs.com/";              QName name = new QName(iNs,"test","tn");            SOAPBodyElement element = body.addBodyElement(name);            element.addChildElement( new QName("content")).setTextContent("sdfsf");            soapMsg.writeTo(System.out);              System.out.println();              System.out.println("---invoke-----");              SOAPMessage response = connection.call(soapMsg,wsdlUrl);            response.writeTo(System.out);}//带附件访问服务中upload方法private static void testSAAJAttachement() throws Exception{String endpointAddress = "http://localhost:8080/ssh_book/services/testWebservice";URL wsdlUrl = new URL(endpointAddress);SOAPConnectionFactory soapConnectionFactory =                SOAPConnectionFactory.newInstance();            SOAPConnection connection =                soapConnectionFactory.createConnection();//创建消息工厂MessageFactory messageFactory = MessageFactory.newInstance();//创建消息    SOAPMessage soapMsg =  messageFactory.createMessage();         //创建附件对象    AttachmentPart attachment = soapMsg.createAttachmentPart(new DataHandler(new FileDataSource(new File(uploadDir,"a.jpg"))));     attachment.setContentId("<" + UUID.randomUUID().toString() + ">");          attachment.setMimeHeader("Content-Transfer-Encoding", "binary");      soapMsg.addAttachmentPart(attachment);    //设置Content-Type          MimeHeaders hd = soapMsg.getMimeHeaders();        hd.setHeader("Content-Type", "application/xop+xml; charset=utf-8; type=\"text/xml\"");      SOAPEnvelope envelope = soapMsg.getSOAPPart().getEnvelope();    SOAPBody soapBody = envelope.getBody();    String iNs = "http://service.bs.com/";      QName qname = new QName(iNs,"upload","ns");    SOAPBodyElement uploadElement = soapBody.addBodyElement(qname);    uploadElement.addChildElement(new QName("arg0")).addTextNode("123456.jpg");    SOAPElement elementData = uploadElement.addChildElement(new QName("arg1"));    //添加XOP支持          elementData.addChildElement(                  new QName("http://www.w3.org/2004/08/xop/include", "Include","xop"))                  .addAttribute(new QName("href"),"cid:" + attachment.getContentId().replaceAll("<", "").replaceAll(">", ""));      soapMsg.writeTo(System.out);          System.out.println();          System.out.println("---invoke-----");          //发送soap消息        SOAPMessage response = connection.call(soapMsg,wsdlUrl);        //输出soap消息        response.writeTo(System.out);                //以下代码是获取soap消息中所有附件信息        /* java.util.Iterator iterator = soapMsg.getAttachments();     while (iterator.hasNext()) {     AttachmentPart attachment = (AttachmentPart)iterator.next();     String id = attachment.getContentId();     String type = attachment.getContentType();     System.out.print("Attachment: " + id + " ,has content type:" + type);     if (type == "text/plain") {     Object content = attachment.getContent();     System.out.println("Attachment " + "contains:\n" + content);      }     }*/}}


0 0
原创粉丝点击