Axis2学习的第一天

 

按照下面,分别建2个工程,一个client(客户端),一个server(服务端)

先实现服务端:

1、编写services.xml文件,该文件是放在aar文件里的\META-INF目录下的:

<?xml version="1.0" encoding="UTF-8"?>
<!-- This file was auto-generated from WSDL -->
<!-- by the Apache Axis2 version: 1.4.1  Built on : Aug 19, 2008 (10:13:39 LKT)
     <parameter name="useOriginalwsdl">false</parameter>
     <parameter name="modifyUserWSDLPortAddress">true</parameter>
 -->
<serviceGroup>
    <service name="axis2Service">    
        <description>  
           This is a sample Web Service.  
        </description>  
        <!-- // ServiceClass指定Java Class的位置,即实现服务的类。  --> 
        <parameter name="ServiceClass" locked="false">com.study.axis2.service.impl.Axis2ServiceImpl</parameter>  
        <!-- // operation 与Java Class中方法名对应。  -->   
        <operation name="user">  
            <!-- // messageReceiver看下文注解。    --> 
               <messageReceiver class="com.study.axis2.receive.Axis2MessageReceiverInOut"/>  
        </operation>  
    </service>  
</serviceGroup>

2、编写Axis2ServiceImpl类:

package com.study.axis2.service.impl;

import com.study.axis2.domain.User;
import com.study.axis2.domain.UserResponse;
import com.study.axis2.service.Axis2Service;

public class Axis2ServiceImpl implements Axis2Service {

    public UserResponse user(User user) {
        // 将in转换为String。
        int userId = user.getUserId();
        String userName = user.getUserName();
        
        System.out.println("USER ID : " + userId + "; USER NAME : " + userName);
        
        UserResponse response = new UserResponse();
        response.setRspCode("0000");
        response.setRspDesc("SUCCESS");
        
        return response;
    }

}

3、编写User和UserResponse类:

package com.study.axis2.domain;

public class User {
    
    private int userId;
    private String userName;
    
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}
package com.study.axis2.domain;

public class UserResponse {
    
    private String rspCode;
    private String rspDesc;
    
    public String getRspCode() {
        return rspCode;
    }
    public void setRspCode(String rspCode) {
        this.rspCode = rspCode;
    }
    public String getRspDesc() {
        return rspDesc;
    }
    public void setRspDesc(String rspDesc) {
        this.rspDesc = rspDesc;
    }
}

4、编写Axis2MessageReceiverInOut类,用来接收报文的,实际上用Axis2ServiceImpl类来处理业务逻辑,但为了省事,略,直接在InOut类里编写了响应报文:

package com.study.axis2.receive;

import java.io.ByteArrayInputStream;
import java.util.Iterator;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.soap.SOAPBody;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.receivers.AbstractInOutMessageReceiver;

public class Axis2MessageReceiverInOut extends AbstractInOutMessageReceiver{
    private static String ENCODEING = "UTF-8";
    private static String NAMING_SPACE = "http://impl.service.axis2.study.com";

    @Override
    public void invokeBusinessLogic(MessageContext envMsg, MessageContext newEnvMsg)
            throws AxisFault {
        System.out.println("------------------------------------");
        String body = envMsg.getEnvelope().getBody().toString();
        System.out.println("request body1 : " + body);
        
        //Axis2Service axis2 = new Axis2ServiceImpl();
        
        StringBuffer soapRequestData = new StringBuffer();
        soapRequestData.append("<userResponse>");
        soapRequestData.append("<rspCode>0000</rspCode>");
        soapRequestData.append("<rspDesc>SUCCESS</rspDesc>");
        soapRequestData.append("</userResponse>");
        
        SOAPEnvelope env = toEnvelope(soapRequestData.toString());
        
        newEnvMsg.setEnvelope(env);
    }
    
    public static SOAPEnvelope toEnvelope(String sourceXml)
    {
        String xmlBody = sourceXml;

        OMFactory of = OMAbstractFactory.getOMFactory();
        OMNamespace bname = of.createOMNamespace(NAMING_SPACE, "");

        SOAPFactory s12f = OMAbstractFactory.getSOAP12Factory();
        SOAPEnvelope s12e = s12f.getDefaultEnvelope();

        try
        {
            byte[] bytes = xmlBody.getBytes(ENCODEING);
            ByteArrayInputStream is = new ByteArrayInputStream(bytes);
            
            StAXOMBuilder builder = new StAXOMBuilder(is);
            
            OMElement elementBody = builder.getDocumentElement();
            //elementBody.setNamespace(bname);
            //addNameSpacePrefix(elementBody, bname);
            
            SOAPBody s12b = s12e.getBody();
            s12b.addChild(elementBody);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return s12e;
    }

    public static OMElement addNameSpacePrefix(OMElement element,
            OMNamespace prefix)
    {
        if (element.getChildElements() != null)
        {
            Iterator<OMElement> it = element.getChildElements();
            element.setNamespace(prefix);
            while (it.hasNext())
            {
                OMElement childelement = (OMElement) it.next();
                childelement.setNamespace(prefix);

                if ((childelement.getChildElements() == null)
                        || (!childelement.getChildElements().hasNext()))
                    continue;
                addChildNameSpacePrefix(childelement.getChildElements(), prefix);
            }
        }

        return element;
    }

    public static void addChildNameSpacePrefix(Iterator element,
            OMNamespace prefix)
    {
        if (element != null)
        {
            while (element.hasNext())
            {
                OMElement childelement = (OMElement) element.next();

                childelement.setNamespace(prefix);
                if ((childelement.getChildElements() == null)
                        || (!childelement.getChildElements().hasNext()))
                    continue;
                addChildNameSpacePrefix(childelement.getChildElements(), prefix);
            }
        }
    }

}

5、将该类和services.xml文件都放在axis2service.aar下 ,并在WEB-INF/services/services.list文件下增加axis2service.aar:

axis2service.aar
version-1.6.2.aar

服务端编写好,发布,http://localhost:8082/axis2_server_150701/services/axis2Service?wsdl

  <?xml version="1.0" encoding="UTF-8" ?> 
- <wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://impl.service.axis2.study.com" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://impl.service.axis2.study.com">
  <wsdl:documentation>axis2Service</wsdl:documentation> 
- <wsdl:types>
- <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://impl.service.axis2.study.com">
- <xs:element name="user">
- <xs:complexType>
- <xs:sequence>
  <xs:element minOccurs="0" name="user" nillable="true" type="xs:anyType" /> 
  </xs:sequence>
  </xs:complexType>
  </xs:element>
- <xs:element name="userResponse">
- <xs:complexType>
- <xs:sequence>
  <xs:element minOccurs="0" name="return" nillable="true" type="xs:anyType" /> 
  </xs:sequence>
  </xs:complexType>
  </xs:element>
  </xs:schema>
  </wsdl:types>
- <wsdl:message name="userRequest">
  <wsdl:part name="parameters" element="ns:user" /> 
  </wsdl:message>
- <wsdl:message name="userResponse">
  <wsdl:part name="parameters" element="ns:userResponse" /> 
  </wsdl:message>
- <wsdl:portType name="axis2ServicePortType">
- <wsdl:operation name="user">
  <wsdl:input message="ns:userRequest" wsaw:Action="urn:user" /> 
  <wsdl:output message="ns:userResponse" wsaw:Action="urn:userResponse" /> 
  </wsdl:operation>
  </wsdl:portType>
- <wsdl:binding name="axis2ServiceSoap11Binding" type="ns:axis2ServicePortType">
  <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" /> 
- <wsdl:operation name="user">
  <soap:operation soapAction="urn:user" style="document" /> 
- <wsdl:input>
  <soap:body use="literal" /> 
  </wsdl:input>
- <wsdl:output>
  <soap:body use="literal" /> 
  </wsdl:output>
  </wsdl:operation>
  </wsdl:binding>
- <wsdl:binding name="axis2ServiceSoap12Binding" type="ns:axis2ServicePortType">
  <soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" /> 
- <wsdl:operation name="user">
  <soap12:operation soapAction="urn:user" style="document" /> 
- <wsdl:input>
  <soap12:body use="literal" /> 
  </wsdl:input>
- <wsdl:output>
  <soap12:body use="literal" /> 
  </wsdl:output>
  </wsdl:operation>
  </wsdl:binding>
- <wsdl:binding name="axis2ServiceHttpBinding" type="ns:axis2ServicePortType">
  <http:binding verb="POST" /> 
- <wsdl:operation name="user">
  <http:operation location="user" /> 
- <wsdl:input>
  <mime:content type="application/xml" part="parameters" /> 
  </wsdl:input>
- <wsdl:output>
  <mime:content type="application/xml" part="parameters" /> 
  </wsdl:output>
  </wsdl:operation>
  </wsdl:binding>
- <wsdl:service name="axis2Service">
- <wsdl:port name="axis2ServiceHttpSoap11Endpoint" binding="ns:axis2ServiceSoap11Binding">
  <soap:address location="http://localhost:8082/axis2_server_150701/services/axis2Service.axis2ServiceHttpSoap11Endpoint/" /> 
  </wsdl:port>
- <wsdl:port name="axis2ServiceHttpSoap12Endpoint" binding="ns:axis2ServiceSoap12Binding">
  <soap12:address location="http://localhost:8082/axis2_server_150701/services/axis2Service.axis2ServiceHttpSoap12Endpoint/" /> 
  </wsdl:port>
- <wsdl:port name="axis2ServiceHttpEndpoint" binding="ns:axis2ServiceHttpBinding">
  <http:address location="http://localhost:8082/axis2_server_150701/services/axis2Service.axis2ServiceHttpEndpoint/" /> 
  </wsdl:port>
  </wsdl:service>
  </wsdl:definitions>

axis2可以访问http://localhost:8082/axis2_server_150701/services/listServices来查看发布了哪些接口:

 

以上服务端已完全搭好,现编写客户端client,服务端增加个User类:

package com.study.axis2.client;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

import com.study.axis2.domain.User;


public class Axis2Client {
    private static String url = "http://localhost:8082/axis2_server_150701/services/axis2Service";

    public static void main(String[] args) {
    
        User user = new User();
        user.setUserId(11111);
        user.setUserName("66666");
        
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        StringBuffer soapRequestData = new StringBuffer();
        soapRequestData.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        soapRequestData
                .append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
                        + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
                        + " xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">");
        soapRequestData.append("<soap12:Body>");
        soapRequestData.append("<user xmlns=\"http://impl.service.axis2.study.com\">");
        soapRequestData.append("<userId>" + user.getUserId() + "</userId>");
        soapRequestData.append("<userName>" + user.getUserName() + "</userName>");
        soapRequestData.append("</user>");
        soapRequestData.append("</soap12:Body>");
        soapRequestData.append("</soap12:Envelope>");
        
        String xml = soapRequestData.toString();
        
        byte[] b;
        
        try
        {
            b = xml.getBytes("utf-8");
            
            System.out.println("request : " + xml);
            InputStream is = new ByteArrayInputStream(b, 0, b.length);
            RequestEntity re = new InputStreamRequestEntity(is, b.length, "application/soap+xml; charset=utf-8");
            method.setRequestEntity(re);
            
            client.executeMethod(method);
            String response = method.getResponseBodyAsString();
            System.out.println("response : " + response);
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
    
}

执行客户端代码,输出(输出结果内容为xml,稍微format下):

request : 
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
    <soap12:Body>
        <user xmlns="http://impl.service.axis2.study.com">
            <userId>11111</userId>
            <userName>yff</userName>
        </user>
    </soap12:Body>
</soap12:Envelope>
response : 
<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
    <soapenv:Body>
        <userResponse>
            <rspCode>0000</rspCode>
            <rspDesc>SUCCESS</rspDesc>
        </userResponse>
    </soapenv:Body>
</soapenv:Envelope>

 

posted @ 2015-07-30 18:24  奋斗?坑  阅读(1428)  评论(0编辑  收藏  举报