使用axis1.4生成的WebService客户端增加用户验证信息

使用axis1.4生成的WebService客户端增加用户验证信息

文章目录

  • 使用axis1.4生成的WebService客户端增加用户验证信息
      • 第一步:调整客户端,增加请求头
      • 第二步:修改服务端代码
      • 第三步:执行客户端程序,发送请求
      • 第四步:通过TCP\IP Monitor监测报文
        • TCP\IP Monitor工具的配置截图如下:
        • 修改客户端发送的端口
        • 执行客户端的请求

提示:由于本文涉及的代码在之前的文章中,所以在阅读本文之前,请先阅读如下内容

《使用axis1.4发布webService服务》,文章链接为:https://blog.csdn.net/Jack_David/article/details/86532983

《使用axis生成WebService调用客户端》,文章链接为:https://blog.csdn.net/Jack_David/article/details/86537327

第一步:调整客户端,增加请求头

1.修改StudentServiceSoapBindingStub类,增加一个方法createAuthInfo(),内容如下:

	/**
	 * 
	 * 为soap报文添加自定义的用户授权信息,这里为用户名和密码
	 * 
	 * @return SOAPHeaderElement对象
	 */
	public SOAPHeaderElement createAuthInfo() {
		SOAPHeaderElement header = new SOAPHeaderElement(
				"http://www.csdn.com/axis/StudentService", "AuthHeadersInfo");
		header.setNamespaceURI("http://www.csdn.com/axis/StudentService");
		try {
			header.addChildElement("userName").setValue("zhangsan");
			header.addChildElement("password").setValue("123pwd");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return header;
	}

2.为soap报文增加请求头,找到StudentServiceSoapBindingStub类的createCall方法,在return _call;之前添加一句:_call.addHeader(createAuthInfo());// 增加用户授权信息

内容如下:

_call.addHeader(createAuthInfo());// 增加用户授权信息

StudentServiceSoapBindingStub类的完整内容如下

/**
 * StudentServiceSoapBindingStub.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package com.csdn.www.axis.StudentService;

import org.apache.axis.message.SOAPHeaderElement;

public class StudentServiceSoapBindingStub extends org.apache.axis.client.Stub
		implements com.csdn.www.axis.StudentService.StudentServiceImpl {
	private java.util.Vector cachedSerClasses = new java.util.Vector();
	private java.util.Vector cachedSerQNames = new java.util.Vector();
	private java.util.Vector cachedSerFactories = new java.util.Vector();
	private java.util.Vector cachedDeserFactories = new java.util.Vector();

	static org.apache.axis.description.OperationDesc[] _operations;

	static {
		_operations = new org.apache.axis.description.OperationDesc[2];
		_initOperationDesc1();
	}

	private static void _initOperationDesc1() {
		org.apache.axis.description.OperationDesc oper;
		org.apache.axis.description.ParameterDesc param;
		oper = new org.apache.axis.description.OperationDesc();
		oper.setName("getStudentInfo");
		param = new org.apache.axis.description.ParameterDesc(
				new javax.xml.namespace.QName("", "studentNo"),
				org.apache.axis.description.ParameterDesc.IN,
				new javax.xml.namespace.QName(
						"http://schemas.xmlsoap.org/soap/encoding/", "string"),
				java.lang.String.class, false, false);
		oper.addParameter(param);
		oper.setReturnType(new javax.xml.namespace.QName(
				"http://schemas.xmlsoap.org/soap/encoding/", "string"));
		oper.setReturnClass(java.lang.String.class);
		oper.setReturnQName(new javax.xml.namespace.QName("",
				"getStudentInfoReturn"));
		oper.setStyle(org.apache.axis.constants.Style.RPC);
		oper.setUse(org.apache.axis.constants.Use.ENCODED);
		_operations[0] = oper;

		oper = new org.apache.axis.description.OperationDesc();
		oper.setName("getStudentMarks");
		param = new org.apache.axis.description.ParameterDesc(
				new javax.xml.namespace.QName("", "studentNo"),
				org.apache.axis.description.ParameterDesc.IN,
				new javax.xml.namespace.QName(
						"http://schemas.xmlsoap.org/soap/encoding/", "string"),
				java.lang.String.class, false, false);
		oper.addParameter(param);
		param = new org.apache.axis.description.ParameterDesc(
				new javax.xml.namespace.QName("", "subjectNo"),
				org.apache.axis.description.ParameterDesc.IN,
				new javax.xml.namespace.QName(
						"http://schemas.xmlsoap.org/soap/encoding/", "string"),
				java.lang.String.class, false, false);
		oper.addParameter(param);
		oper.setReturnType(new javax.xml.namespace.QName(
				"http://schemas.xmlsoap.org/soap/encoding/", "string"));
		oper.setReturnClass(java.lang.String.class);
		oper.setReturnQName(new javax.xml.namespace.QName("",
				"getStudentMarksReturn"));
		oper.setStyle(org.apache.axis.constants.Style.RPC);
		oper.setUse(org.apache.axis.constants.Use.ENCODED);
		_operations[1] = oper;

	}

	public StudentServiceSoapBindingStub() throws org.apache.axis.AxisFault {
		this(null);
	}

	public StudentServiceSoapBindingStub(java.net.URL endpointURL,
			javax.xml.rpc.Service service) throws org.apache.axis.AxisFault {
		this(service);
		super.cachedEndpoint = endpointURL;
	}

	public StudentServiceSoapBindingStub(javax.xml.rpc.Service service)
			throws org.apache.axis.AxisFault {
		if (service == null) {
			super.service = new org.apache.axis.client.Service();
		} else {
			super.service = service;
		}
		((org.apache.axis.client.Service) super.service)
				.setTypeMappingVersion("1.2");
	}

	protected org.apache.axis.client.Call createCall()
			throws java.rmi.RemoteException {
		try {
			org.apache.axis.client.Call _call = super._createCall();
			if (super.maintainSessionSet) {
				_call.setMaintainSession(super.maintainSession);
			}
			if (super.cachedUsername != null) {
				_call.setUsername(super.cachedUsername);
			}
			if (super.cachedPassword != null) {
				_call.setPassword(super.cachedPassword);
			}
			if (super.cachedEndpoint != null) {
				_call.setTargetEndpointAddress(super.cachedEndpoint);
			}
			if (super.cachedTimeout != null) {
				_call.setTimeout(super.cachedTimeout);
			}
			if (super.cachedPortName != null) {
				_call.setPortName(super.cachedPortName);
			}
			java.util.Enumeration keys = super.cachedProperties.keys();
			while (keys.hasMoreElements()) {
				java.lang.String key = (java.lang.String) keys.nextElement();
				_call.setProperty(key, super.cachedProperties.get(key));
			}
			_call.addHeader(createAuthInfo());// 增加用户授权信息
			return _call;
		} catch (java.lang.Throwable _t) {
			throw new org.apache.axis.AxisFault(
					"Failure trying to get the Call object", _t);
		}
	}

	public java.lang.String getStudentInfo(java.lang.String studentNo)
			throws java.rmi.RemoteException {
		if (super.cachedEndpoint == null) {
			throw new org.apache.axis.NoEndPointException();
		}
		org.apache.axis.client.Call _call = createCall();
		_call.setOperation(_operations[0]);
		_call.setUseSOAPAction(true);
		_call.setSOAPActionURI("");
		_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
		_call.setOperationName(new javax.xml.namespace.QName(
				"http://www.csdn.com/axis/StudentService", "getStudentInfo"));

		setRequestHeaders(_call);
		setAttachments(_call);
		try {
			java.lang.Object _resp = _call
					.invoke(new java.lang.Object[] { studentNo });

			if (_resp instanceof java.rmi.RemoteException) {
				throw (java.rmi.RemoteException) _resp;
			} else {
				extractAttachments(_call);
				try {
					return (java.lang.String) _resp;
				} catch (java.lang.Exception _exception) {
					return (java.lang.String) org.apache.axis.utils.JavaUtils
							.convert(_resp, java.lang.String.class);
				}
			}
		} catch (org.apache.axis.AxisFault axisFaultException) {
			throw axisFaultException;
		}
	}

	public java.lang.String getStudentMarks(java.lang.String studentNo,
			java.lang.String subjectNo) throws java.rmi.RemoteException {
		if (super.cachedEndpoint == null) {
			throw new org.apache.axis.NoEndPointException();
		}
		org.apache.axis.client.Call _call = createCall();
		_call.setOperation(_operations[1]);
		_call.setUseSOAPAction(true);
		_call.setSOAPActionURI("");
		_call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS);
		_call.setOperationName(new javax.xml.namespace.QName(
				"http://www.csdn.com/axis/StudentService", "getStudentMarks"));

		setRequestHeaders(_call);
		setAttachments(_call);
		try {
			java.lang.Object _resp = _call.invoke(new java.lang.Object[] {
					studentNo, subjectNo });

			if (_resp instanceof java.rmi.RemoteException) {
				throw (java.rmi.RemoteException) _resp;
			} else {
				extractAttachments(_call);
				try {
					return (java.lang.String) _resp;
				} catch (java.lang.Exception _exception) {
					return (java.lang.String) org.apache.axis.utils.JavaUtils
							.convert(_resp, java.lang.String.class);
				}
			}
		} catch (org.apache.axis.AxisFault axisFaultException) {
			throw axisFaultException;
		}
	}

	/**
	 * 
	 * 为soap报文添加自定义的用户授权信息,这里为用户名和密码
	 * 
	 * @return SOAPHeaderElement对象
	 */
	public SOAPHeaderElement createAuthInfo() {
		SOAPHeaderElement header = new SOAPHeaderElement(
				"http://www.csdn.com/axis/StudentService", "AuthHeadersInfo");
		header.setNamespaceURI("http://www.csdn.com/axis/StudentService");
		try {
			header.addChildElement("userName").setValue("zhangsan");
			header.addChildElement("password").setValue("123pwd");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return header;
	}

}

第二步:修改服务端代码

回到StudApp中,修改我们的StudAppUtil的invokeInnerService方法,增加如下代码:

		//增加验证用户授权信息   BEGIN
		MessageContext msgContext = MessageContext.getCurrentContext();
		try {
			Iterator<SOAPElement> iterator = msgContext.getMessage()
					.getSOAPHeader().getChildElements();
			while (iterator.hasNext()) {
				SOAPElement ele = iterator.next();
				Iterator<SOAPElement> iterator2 = ele.getChildElements();
				while (iterator2.hasNext()) {
					SOAPElement element = iterator2.next();
					String Name = element.getNodeName();
					String value = element.getValue();
					System.out.println("Name=" + Name + ",Value=" + value);
				}
			}
		} catch (SOAPException e) {
			e.printStackTrace();
		}
		//增加验证用户授权信息   END

StudAppUtil类的完整代码如下:

package com.csdn.utils;

import java.util.Iterator;
import java.util.Map;

import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;

import org.apache.axis.MessageContext;

/**
 * 
 * 公共学生信息工具类
 * 
 * @author Jack_David
 *
 */
public class StudAppUtil {

	/**
	 * 
	 * 调用内部服务
	 * 
	 * @param studentNo
	 *            学生学号
	 * @param txnCode
	 *            交易码
	 * @return 返回交易的结果信息
	 */
	@SuppressWarnings("unchecked")
	public static String invokeInnerService(Map<String, Object> dataMap,
			String txnCode) {

		String responseInfo = "";

		//增加验证用户授权信息   BEGIN
		MessageContext msgContext = MessageContext.getCurrentContext();
		try {
			Iterator<SOAPElement> iterator = msgContext.getMessage()
					.getSOAPHeader().getChildElements();
			while (iterator.hasNext()) {
				SOAPElement ele = iterator.next();
				Iterator<SOAPElement> iterator2 = ele.getChildElements();
				while (iterator2.hasNext()) {
					SOAPElement element = iterator2.next();
					String Name = element.getNodeName();
					String value = element.getValue();
					System.out.println("Name=" + Name + ",Value=" + value);
				}
			}
		} catch (SOAPException e) {
			e.printStackTrace();
		}
		//增加验证用户授权信息   END

		if ("getStudentInfo".equals(txnCode)) {
			String studentNo = (String) dataMap.get("studentNo");
			responseInfo = "学号=" + studentNo + ",姓名=张三,年龄=18,专业=计算机科学";
		} else if ("getStudentMarks".equals(txnCode)) {
			String studentNo = (String) dataMap.get("studentNo");
			String subjectNo = (String) dataMap.get("subjectNo");
			responseInfo = "学号=" + studentNo + ",学科号=" + subjectNo + ",成绩=98";
		}
		return responseInfo;
	}

}

第三步:执行客户端程序,发送请求

执行客户端的StudClient的mian方法,发起调用两个接口的请求,观察服务端和客户端的相关信息

客户端正常收到响应,如下图:

使用axis1.4生成的WebService客户端增加用户验证信息_第1张图片

服务端收到了客户端发送的用户验证信息,如下图:

使用axis1.4生成的WebService客户端增加用户验证信息_第2张图片

第四步:通过TCP\IP Monitor监测报文

我们可以使用Eclipse自带的代理工具TCP\IP Monitor来监测请求及响应报文,思路如下:

1.TCP\IP Monitor监听8080端口,转发到本机的8090端口上去

2.客户端发送报文的时候,将报文发送到8080端口

说明:不会使用TCP\IP Monitor该工具的,请参考链接:https://www.cnblogs.com/liuhongfeng/p/4187572.html?utm_source=tuicool&utm_medium=referral

TCP\IP Monitor工具的配置截图如下:

使用axis1.4生成的WebService客户端增加用户验证信息_第3张图片

修改客户端发送的端口

修改StudentServiceImplServiceLocator类的请求发送端口

	private java.lang.String StudentService_address = "http://127.0.0.1:8080/StudApp/services/StudentService";

执行客户端的请求

执行StudClient的两个请求,观察TCP\IP Monitor中的抓包信息,可以看到这两次的完整的请求以及相应信息,如下图:

使用axis1.4生成的WebService客户端增加用户验证信息_第4张图片

我们把两次请求的报文拿出来单独看,会发现已经包含了我们指定的用户验证信息,如下图:

使用axis1.4生成的WebService客户端增加用户验证信息_第5张图片

你可能感兴趣的:(Java,WebService)