使用Axis发送SOAP请求

使用的jar

compile group: 'org.apache.axis', name: 'axis', version: '1.4'
    // https://mvnrepository.com/artifact/org.apache.axis/axis-jaxrpc
compile group: 'org.apache.axis', name: 'axis-jaxrpc', version: '1.4'

    // https://mvnrepository.com/artifact/commons-logging/commons-logging
compile group: 'commons-logging', name: 'commons-logging', version: '1.2'
    // https://mvnrepository.com/artifact/commons-discovery/commons-discovery
compile group: 'commons-discovery', name: 'commons-discovery', version: '0.5'
    // https://mvnrepository.com/artifact/wsdl4j/wsdl4j
compile group: 'wsdl4j', name: 'wsdl4j', version: '1.6.3'

本文章为测试Mantisbt的SOAP API时使用的代码。

SOAP客户端

package soap;

import java.rmi.RemoteException;

import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.description.ParameterDesc;
import org.apache.axis.soap.SOAPConstants;

public class ConnectMantisService {
	
	public static void main(String[] args) throws RemoteException {
		ConnectMantisService service = new ConnectMantisService();
		service.mc_version();
		service.mc_login();
	}
	
	public void mc_login() {
		String webServiceNamespace = "http://172.21.129.54/mantisbt/api/soap/mantisconnect.php/mc_login";
		String endpoint = "http://172.21.129.54/mantisbt/api/soap/mantisconnect.php";
		
		Service service = new Service();
		try {
			Call call = (Call) service.createCall();
			call.setSOAPActionURI(webServiceNamespace);
			call.setTargetEndpointAddress(endpoint);
			call.setOperationName(new QName("http://futureware.biz/mantisconnect","mc_login"));
			OperationDesc opera = new OperationDesc();
			opera.setName("mc_login");
			ParameterDesc paraDesc ;
			ParameterDesc paraDesc2 ;
			paraDesc = new ParameterDesc(new QName("", "username"), ParameterDesc.IN, new QName("http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false);
			opera.addParameter(paraDesc);
			paraDesc2 = new ParameterDesc(new QName("", "password"), ParameterDesc.IN, new QName("http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false);
			opera.addParameter(paraDesc2);
			opera.setReturnClass(UserData.class);
			opera.setReturnType(new QName("http://futureware.biz/mantisconnect", "UserData"));
			opera.setReturnQName(new QName("", "return"));
			opera.setStyle(org.apache.axis.constants.Style.RPC);
			opera.setUse(org.apache.axis.constants.Use.ENCODED);
			call.setOperation(opera);
			call.setSOAPVersion(SOAPConstants.SOAP11_CONSTANTS);
			Object result = call.invoke(new Object[] {"lizl","lizl@123"});
			
			System.out.println(((UserData) result).getAccount_data().getName());
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void mc_version() {
		String webServiceNamespace = "https://mantisbt.org/bugs/api/soap/mantisconnect.php/mc_version";
		String endpoint = "https://mantisbt.org/bugs/api/soap/mantisconnect.php";
		
		Service service = new Service();
		try {
			Call call = (Call) service.createCall();
			call.setSOAPActionURI(webServiceNamespace);
			call.setTargetEndpointAddress(endpoint);
			call.setOperationName(new QName("http://futureware.biz/mantisconnect","mc_version"));
			OperationDesc opera = new OperationDesc();
			opera.setName("mc_version");
			opera.setReturnType(new QName("http://www.w3.org/2001/XMLSchema", "string"));
			opera.setReturnClass(java.lang.String.class);
			opera.setReturnQName(new QName("", "return"));
			opera.setStyle(org.apache.axis.constants.Style.RPC);
			opera.setUse(org.apache.axis.constants.Use.ENCODED);
			call.setOperation(opera);
			Object result = call.invoke(new Object[] {});
			System.out.println((String) result);
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

UserData实体类

package soap;

import java.io.Serializable;
import java.math.BigInteger;

import javax.xml.namespace.QName;

import org.apache.axis.description.ElementDesc;
import org.apache.axis.description.TypeDesc;
import org.apache.axis.encoding.Deserializer;
import org.apache.axis.encoding.Serializer;
import org.apache.axis.encoding.ser.BeanDeserializer;
import org.apache.axis.encoding.ser.BeanSerializer;

public class UserData  implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7051603656731578765L;
	
	private AccountData account_data;

	private BigInteger access_level;
	
	private String timezone;
	
	public UserData() {}
	
	public UserData(AccountData account_data, BigInteger access_level, String timezone) {
		this.account_data = account_data;
		this.access_level = access_level;
		this.timezone = timezone;
	}

	public BigInteger getAccess_level() {
		return access_level;
	}

	public void setAccess_level(BigInteger access_level) {
		this.access_level = access_level;
	}

	public String getTimezone() {
		return timezone;
	}

	public void setTimezone(String timezone) {
		this.timezone = timezone;
	}

	public AccountData getAccount_data() {
		return account_data;
	}

	public void setAccount_data(AccountData account_data) {
		this.account_data = account_data;
	}
	
	private static TypeDesc typeDesc =
	        new TypeDesc(UserData.class, true);

	    static {
	        typeDesc.setXmlType(new QName("http://futureware.biz/mantisconnect", "UserData"));
	        ElementDesc elemField = new ElementDesc();
	        elemField.setFieldName("account_data");
	        elemField.setXmlName(new QName("", "account_data"));
	        elemField.setXmlType(new QName("http://futureware.biz/mantisconnect", "AccountData"));
	        elemField.setMinOccurs(0);
	        elemField.setNillable(false);
	        typeDesc.addFieldDesc(elemField);
	        elemField = new ElementDesc();
	        elemField.setFieldName("access_level");
	        elemField.setXmlName(new QName("", "access_level"));
	        elemField.setXmlType(new QName("http://www.w3.org/2001/XMLSchema", "integer"));
	        elemField.setMinOccurs(0);
	        elemField.setNillable(false);
	        typeDesc.addFieldDesc(elemField);
	        elemField = new ElementDesc();
	        elemField.setFieldName("timezone");
	        elemField.setXmlName(new QName("", "timezone"));
	        elemField.setXmlType(new QName("http://www.w3.org/2001/XMLSchema", "string"));
	        elemField.setMinOccurs(0);
	        elemField.setNillable(false);
	        typeDesc.addFieldDesc(elemField);
	    }

	    /**
	     * Return type metadata object
	     */
	    public static TypeDesc getTypeDesc() {
	        return typeDesc;
	    }

	    /**
	     * Get Custom Serializer
	     */
	    public static Serializer getSerializer(
	           String mechType, 
	           Class _javaType,  
	           QName _xmlType) {
	        return 
	          new  BeanSerializer(
	            _javaType, _xmlType, typeDesc);
	    }

	    /**
	     * Get Custom Deserializer
	     */
	    public static Deserializer getDeserializer(
	           String mechType, 
	           Class _javaType,  
	           QName _xmlType) {
	        return 
	          new  BeanDeserializer(
	            _javaType, _xmlType, typeDesc);
	    }
	
}

AccountData实体类

package soap;

import java.io.Serializable;

public class AccountData implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -7939532123587779880L;

	private java.math.BigInteger id;

    private java.lang.String name;

    private java.lang.String real_name;

    private java.lang.String email;
    
    public AccountData() {
    }

    public AccountData(
           java.math.BigInteger id,
           java.lang.String name,
           java.lang.String real_name,
           java.lang.String email) {
           this.id = id;
           this.name = name;
           this.real_name = real_name;
           this.email = email;
    }

	public java.math.BigInteger getId() {
		return id;
	}

	public void setId(java.math.BigInteger id) {
		this.id = id;
	}

	public java.lang.String getName() {
		return name;
	}

	public void setName(java.lang.String name) {
		this.name = name;
	}

	public java.lang.String getReal_name() {
		return real_name;
	}

	public void setReal_name(java.lang.String real_name) {
		this.real_name = real_name;
	}

	public java.lang.String getEmail() {
		return email;
	}

	public void setEmail(java.lang.String email) {
		this.email = email;
	}
    
	// Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(AccountData.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://futureware.biz/mantisconnect", "AccountData"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("id");
        elemField.setXmlName(new javax.xml.namespace.QName("", "id"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "integer"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("name");
        elemField.setXmlName(new javax.xml.namespace.QName("", "name"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("real_name");
        elemField.setXmlName(new javax.xml.namespace.QName("", "real_name"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("email");
        elemField.setXmlName(new javax.xml.namespace.QName("", "email"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType, 
           java.lang.Class _javaType,  
           javax.xml.namespace.QName _xmlType) {
        return 
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType, 
           java.lang.Class _javaType,  
           javax.xml.namespace.QName _xmlType) {
        return 
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }
    

}

Mantis 服务端执行接收SOAP请求 (为PHP代码)

<?php
# MantisBT - A PHP based bugtracking system

# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MantisBT.  If not, see <http://www.gnu.org/licenses/>.

/**
 * A webservice interface to Mantis Bug Tracker
 *
 * @package MantisBT
 * @copyright Copyright 2004  Victor Boctor - [email protected]
 * @copyright Copyright 2005  MantisBT Team - [email protected]
 * @link http://www.mantisbt.org
 */

# Path to MantisBT is assumed to be the grand parent directory.  If this is not
# the case, then this variable should be set to the MantisBT path.
# This can not be a configuration option, then MantisConnect configuration
# needs MantisBT to be included first to make use of the constants and possibly
# configuration defined in MantisBT.
$t_mantis_dir = dirname( dirname( dirname( __FILE__ ) ) ) . DIRECTORY_SEPARATOR;

# Overrides for behaviors for core.php and its dependencies
$g_bypass_headers = true;
$g_bypass_error_handler = true;

require_once( $t_mantis_dir . 'core.php' );

/**
 * Checks if the request for the webservice is a documentation request (eg:
 * WSDL) or an actual webservice call.
 * @return boolean
 */
function mci_is_webservice_call() {
	if( isset( $_SERVER['QUERY_STRING'] ) ) {
		$t_qs = $_SERVER['QUERY_STRING'];
	} else if( isset( $GLOBALS['QUERY_STRING'] ) ) {
		$t_qs = $GLOBALS['QUERY_STRING'];
	}

	if( isset( $t_qs ) && preg_match( '/wsdl/', $t_qs ) ) {
		return false;
	} else {
		return true;
	}
}

# If SOAP extension is not enabled, error out.
if( !extension_loaded( 'soap' ) ) {
	echo 'PHP SOAP extension is not enabled.';
	exit();
}

if( !mci_is_webservice_call() ) {
	# if we have a documentation request, do some tidy up to prevent lame bot loops e.g. /mantisconnect.php/mc_enum_etas/mc_project_get_versions/
	$t_parts = explode( 'mantisconnect.php/', strtolower( $_SERVER['SCRIPT_NAME'] ), 2 );
	if( isset( $t_parts[1] ) && (strlen( $t_parts[1] ) > 0 ) ) {
		echo 'This is not a SOAP webservice request, for documentation, see ' .  $t_parts[0] . 'mantisconnect.php';
		exit();
	}

	header( 'Content-Type: text/xml' );
	$t_wsdl = file_get_contents( 'mantisconnect.wsdl' );
	$t_wsdl = str_replace( 'http://www.mantisbt.org/bugs/api/soap/mantisconnect.php', config_get_global( 'path' ).'api/soap/mantisconnect.php', $t_wsdl );
	echo $t_wsdl;
	exit();
}

require_once( 'mc_core.php' );

set_error_handler( 'mc_error_handler' );
set_exception_handler( 'mc_error_exception_handler' );

$t_server = new SoapServer( 'mantisconnect.wsdl',
	array( 'features' => SOAP_USE_XSI_ARRAY_TYPE + SOAP_SINGLE_ELEMENT_ARRAYS )
);

$t_server->addFunction( SOAP_FUNCTIONS_ALL );
$t_server->handle();

PHP服务器端处理请求

<?php
# MantisBT - A PHP based bugtracking system

# MantisBT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# MantisBT is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with MantisBT.  If not, see <http://www.gnu.org/licenses/>.

/**
 * A webservice interface to Mantis Bug Tracker
 *
 * @package MantisBT
 * @copyright Copyright 2004  Victor Boctor - [email protected]
 * @copyright Copyright 2005  MantisBT Team - [email protected]
 * @link http://www.mantisbt.org
 */

/**
 * Webservice APIs
 *
 * @uses api_token_api.php
 */

require_api( 'api_token_api.php' );

use Mantis\Exceptions\ClientException;
use Mantis\Exceptions\LegacyApiFaultException;
/**
 * Get the MantisConnect webservice version.
 * @return string
 */
function mc_version() {
	return MANTIS_VERSION;
}

/**
 * Attempts to login the user.
 * If logged in successfully, return user information.
 * If failed to login in, then throw a fault.
 * @param string $p_username Login username.
 * @param string $p_password Login password.
 * @return array Array of user data for the current API user
 */
function mc_login( $p_username, $p_password ) {
	$t_user_id = mci_check_login( $p_username, $p_password );
	if( $t_user_id === false ) {
		return mci_fault_login_failed();
	}

	return mci_user_get( $t_user_id );
}

php服务端wsdl 只节选了本文中使用到的mc_version和mc_login,详细内容可以通过https://www.mantisbt.org/bugs/api/soap/mantisconnect.php?wsdl查看

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="wsdl-viewer.xsl"?>
<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://futureware.biz/mantisconnect" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://futureware.biz/mantisconnect">
<types>
<xsd:schema targetNamespace="http://futureware.biz/mantisconnect">
 <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
 <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/"/>
 <xsd:complexType name="IntegerArray">
  <xsd:complexContent>
   <xsd:restriction base="SOAP-ENC:Array">
    <xsd:attribute ref="SOAP-ENC:arrayType" wsdl:arrayType="xsd:integer[]"/>
   </xsd:restriction>
  </xsd:complexContent>
 </xsd:complexType>
 <xsd:complexType name="StringArray">
  <xsd:complexContent>
   <xsd:restriction base="SOAP-ENC:Array">
    <xsd:attribute ref="SOAP-ENC:arrayType" wsdl:arrayType="xsd:string[]"/>
   </xsd:restriction>
  </xsd:complexContent>
 </xsd:complexType>
 <xsd:complexType name="ObjectRef">
  <xsd:all>
   <xsd:element name="id" type="xsd:integer" minOccurs="0"/>
   <xsd:element name="name" type="xsd:string" minOccurs="0"/>
  </xsd:all>
 </xsd:complexType>
 <xsd:complexType name="ObjectRefArray">
  <xsd:complexContent>
   <xsd:restriction base="SOAP-ENC:Array">
    <xsd:attribute ref="SOAP-ENC:arrayType" wsdl:arrayType="tns:ObjectRef[]"/>
   </xsd:restriction>
  </xsd:complexContent>
 </xsd:complexType>
 <xsd:complexType name="AccountData">
  <xsd:all>
   <xsd:element name="id" type="xsd:integer" minOccurs="0"/>
   <xsd:element name="name" type="xsd:string" minOccurs="0"/>
   <xsd:element name="real_name" type="xsd:string" minOccurs="0"/>
   <xsd:element name="email" type="xsd:string" minOccurs="0"/>
  </xsd:all>
 </xsd:complexType>
 <xsd:complexType name="UserData">
  <xsd:all>
   <xsd:element name="account_data" type="tns:AccountData" minOccurs="0"/>
   <xsd:element name="access_level" type="xsd:integer" minOccurs="0"/>
   <xsd:element name="timezone" type="xsd:string" minOccurs="0"/>
  </xsd:all>
 </xsd:complexType>
</xsd:schema>
</types>
<message name="mc_versionRequest"></message>
<message name="mc_versionResponse">
  <part name="return" type="xsd:string" /></message>
<message name="mc_loginRequest">
  <part name="username" type="xsd:string" />
  <part name="password" type="xsd:string" /></message>
<message name="mc_loginResponse">
  <part name="return" type="tns:UserData" /></message>
<portType name="MantisConnectPortType">
  <operation name="mc_version">
    <input message="tns:mc_versionRequest"/>
    <output message="tns:mc_versionResponse"/>
  </operation>
  <operation name="mc_login">
    <documentation>Log the user in and get their information.</documentation>
    <input message="tns:mc_loginRequest"/>
    <output message="tns:mc_loginResponse"/>
  </operation>
</portType>
<binding name="MantisConnectBinding" type="tns:MantisConnectPortType">
  <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
  <operation name="mc_version">
    <soap:operation soapAction="http://www.mantisbt.org/bugs/api/soap/mantisconnect.php/mc_version" style="rpc"/>
    <input><soap:body use="encoded" namespace="http://futureware.biz/mantisconnect" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/></input>
    <output><soap:body use="encoded" namespace="http://futureware.biz/mantisconnect" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/></output>
  </operation>
  <operation name="mc_login">
    <soap:operation soapAction="http://www.mantisbt.org/bugs/api/soap/mantisconnect.php/mc_login" style="rpc"/>
    <input><soap:body use="encoded" namespace="http://futureware.biz/mantisconnect" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/></input>
    <output><soap:body use="encoded" namespace="http://futureware.biz/mantisconnect" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/></output>
  </operation>  
</binding>
<service name="MantisConnect">
  <port name="MantisConnectPort" binding="tns:MantisConnectBinding">
    <soap:address location="http://www.mantisbt.org/bugs/api/soap/mantisconnect.php"/>
  </port>
</service>
</definitions>

猜你喜欢

转载自blog.csdn.net/muziwenrong/article/details/82783379