axis,jax-ws,xfire客户端调用分析,以及webservice万能客户端

最近一个项目需要调用一个webservice接口,遇到一个问题.项目中的jdom版本为0.9.而webservice client需要用到jdom1.0 如果将jdom版本升级则会造成现有系统异常.
因此需要在不改变现有项目jar的情况下解决这个问题.service端使用的jax-ws2.

wsdl如下:

Java代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?><!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.1 in JDK 6. --><!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.1 in JDK 6. --><definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.hua-xia.com.cn/ZySearch" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://www.hua-xia.com.cn/ZySearch" name="UserLinkWebServiceService">   
  2. <types></types>   
  3. <message name="getUserLink">   
  4. <part name="linkNo" type="xsd:string"></part>   
  5. </message>   
  6. <message name="getUserLinkResponse">   
  7. <part name="returnVal" type="xsd:string"></part>   
  8. </message>   
  9. <portType name="UserLinkWebService">   
  10. <operation name="getUserLink" parameterOrder="linkNo">   
  11. <input message="tns:getUserLink"></input>   
  12. <output message="tns:getUserLinkResponse"></output>   
  13. </operation>   
  14. </portType>   
  15. <binding name="UserLinkWebServicePortBinding" type="tns:UserLinkWebService">   
  16. <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"></soap:binding>   
  17. <operation name="getUserLink">   
  18. <soap:operation soapAction="getUserLink"></soap:operation>   
  19. <input>   
  20. <soap:body use="literal" namespace="http://www.hua-xia.com.cn/ZySearch"></soap:body>   
  21. </input>   
  22. <output>   
  23. <soap:body use="literal" namespace="http://www.hua-xia.com.cn/ZySearch"></soap:body>   
  24. </output>   
  25. </operation>   
  26. </binding>   
  27. <service name="UserLinkWebServiceService">   
  28. <port name="UserLinkWebServicePort" binding="tns:UserLinkWebServicePortBinding">   
  29. <soap:address location="http://192.168.1.1.154:9010/ZySearch"></soap:address>   
  30. </port>   
  31. </service>   
  32. </definitions>  
<?xml version="1.0" encoding="UTF-8"?><!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.1 in JDK 6. --><!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.1 in JDK 6. --><definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.hua-xia.com.cn/ZySearch" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://www.hua-xia.com.cn/ZySearch" name="UserLinkWebServiceService">
<types></types>
<message name="getUserLink">
<part name="linkNo" type="xsd:string"></part>
</message>
<message name="getUserLinkResponse">
<part name="returnVal" type="xsd:string"></part>
</message>
<portType name="UserLinkWebService">
<operation name="getUserLink" parameterOrder="linkNo">
<input message="tns:getUserLink"></input>
<output message="tns:getUserLinkResponse"></output>
</operation>
</portType>
<binding name="UserLinkWebServicePortBinding" type="tns:UserLinkWebService">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"></soap:binding>
<operation name="getUserLink">
<soap:operation soapAction="getUserLink"></soap:operation>
<input>
<soap:body use="literal" namespace="http://www.hua-xia.com.cn/ZySearch"></soap:body>
</input>
<output>
<soap:body use="literal" namespace="http://www.hua-xia.com.cn/ZySearch"></soap:body>
</output>
</operation>
</binding>
<service name="UserLinkWebServiceService">
<port name="UserLinkWebServicePort" binding="tns:UserLinkWebServicePortBinding">
<soap:address location="http://192.168.1.1.154:9010/ZySearch"></soap:address>
</port>
</service>
</definitions>




1.xfire调用
对方给我们的client是使用xfire的client调用,代码如下:
Java代码 复制代码  收藏代码
  1. package com.zhongying.bussserv.common;   
  2.   
  3. import java.net.URL;   
  4. import java.util.Map;   
  5. import org.codehaus.xfire.client.Client;   
  6. import com.thoughtworks.xstream.XStream;   
  7. import com.thoughtworks.xstream.io.xml.DomDriver;   
  8.   
  9. public class Test {   
  10.   
  11.   
  12.     public static void main(String[] args) {   
  13.            
  14.         String url = "http://192.168.1.1:8000/RES_Searcher/service/IUserLinkWebService?wsdl";   
  15.            
  16.         Client client;   
  17.         try {   
  18.             client = new Client(new URL(url));   
  19.             Object params[] = {"123456"};   
  20.             String result = (String)client.invoke("getUserLink", params)[0];   
  21.             XStream xStream = new XStream(new DomDriver());   
  22.             Map map = (Map)xStream.fromXML(result);   
  23.         } catch (Exception e) {   
  24.            
  25.             e.printStackTrace();   
  26.         }   
  27.     }   
  28.   
  29. }  
package com.zhongying.bussserv.common;

import java.net.URL;
import java.util.Map;
import org.codehaus.xfire.client.Client;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class Test {


	public static void main(String[] args) {
		
        String url = "http://192.168.1.1:8000/RES_Searcher/service/IUserLinkWebService?wsdl";
        
        Client client;
		try {
			client = new Client(new URL(url));
			Object params[] = {"123456"};
	        String result = (String)client.invoke("getUserLink", params)[0];
	        XStream xStream = new XStream(new DomDriver());
	        Map map = (Map)xStream.fromXML(result);
		} catch (Exception e) {
		
			e.printStackTrace();
		}
	}

}




2.axis调用


但是由于jar包的原因,我们不能使用上面的方法,想出的第一个解决方案是使用axis的客户端来调用接口,代码如下:

Java代码 复制代码  收藏代码
  1.   
  2. import java.util.Iterator;   
  3. import java.util.Map;   
  4. import java.util.Map.Entry;   
  5. import javax.xml.namespace.QName;   
  6. import org.apache.axis.client.Call;   
  7. import org.apache.axis.client.Service;   
  8. import com.thoughtworks.xstream.XStream;   
  9. import com.thoughtworks.xstream.io.xml.DomDriver;   
  10.   
  11. public class TestReflection {   
  12.   
  13.     public static void main(String[] arg) {   
  14.   
  15.         String url = "http://192.168.1.1:9010/ZySearch";   
  16.   
  17.         try {   
  18.   
  19.             Service service = new Service();   
  20.             Call call = (Call) service.createCall();   
  21.             // 设置调用服务地址   
  22.             call.setTargetEndpointAddress(new java.net.URL(url));   
  23.                
  24.             //此处一定要配置wsdl的namespace参数http://www.hua-xia.com.cn/ZySearch   
  25.             call.setOperationName(new QName("http://www.hua-xia.com.cn/ZySearch""getUserLink"));   
  26.   
  27.             //此处需要配置传入参数类型与参数名称,如果未设置jax-ws则无法接受参数,会认为传入的参数为null   
  28.             call.addParameter("linkNo",org.apache.axis.encoding.XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);   
  29.             //如果设置类传入参数类型,此处也需要设置返回参数类型   
  30.             call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);   
  31.             call.setUseSOAPAction(true);   
  32.             call.setSOAPActionURI(url);   
  33.   
  34.             String result = (String) call.invoke(new Object[] { "AD0006526305" });   
  35.   
  36.             XStream xStream = new XStream(new DomDriver());   
  37.             Map map = (Map) xStream.fromXML(result);   
  38.   
  39.             Iterator it = map.entrySet().iterator();   
  40.   
  41.             while (it.hasNext()) {   
  42.   
  43.                 Map.Entry enty = (Entry) it.next();   
  44.   
  45.                 System.out.println(enty.getKey() + ":" + enty.getValue());   
  46.   
  47.             }   
  48.         } catch (Exception e) {   
  49.   
  50.             e.printStackTrace();   
  51.         }   
  52.   
  53.     }   
  54. }  
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.namespace.QName;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class TestReflection {

	public static void main(String[] arg) {

		String url = "http://192.168.1.1:9010/ZySearch";

		try {

			Service service = new Service();
			Call call = (Call) service.createCall();
			// 设置调用服务地址
			call.setTargetEndpointAddress(new java.net.URL(url));
			
			//此处一定要配置wsdl的namespace参数http://www.hua-xia.com.cn/ZySearch
			call.setOperationName(new QName("http://www.hua-xia.com.cn/ZySearch", "getUserLink"));

			//此处需要配置传入参数类型与参数名称,如果未设置jax-ws则无法接受参数,会认为传入的参数为null
			call.addParameter("linkNo",org.apache.axis.encoding.XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);
			//如果设置类传入参数类型,此处也需要设置返回参数类型
			call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);
			call.setUseSOAPAction(true);
			call.setSOAPActionURI(url);

			String result = (String) call.invoke(new Object[] { "AD0006526305" });

			XStream xStream = new XStream(new DomDriver());
			Map map = (Map) xStream.fromXML(result);

			Iterator it = map.entrySet().iterator();

			while (it.hasNext()) {

				Map.Entry enty = (Entry) it.next();

				System.out.println(enty.getKey() + ":" + enty.getValue());

			}
		} catch (Exception e) {

			e.printStackTrace();
		}

	}
}


测试后发现,此方式可以调用xfire和jax-ws的service,但是如果未设置传入参数类型名称,jax-ws认为传入的参数为null.所以一下步骤在调用jax-ws的service时一定要设置
      //此处需要配置传入参数类型与参数名称,如果未设置jax-ws则无法接受参数,会认为传入的参数为null
call.addParameter("linkNo",org.apache.axis.encoding.XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);
//如果设置类传入参数类型,此处也需要设置返回参数类型
call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);
call.setUseSOAPAction(true);
call.setSOAPActionURI(url);

3.http模拟调用


由于开始对axis的了解有限,在写axis调用是总是有问题,于是便想了另外一个方法,这个方法有点剑走偏锋.但是适用性却很强,因为调用的是java自带的api不会产生兼容性问题.
大家知道webservice请求实际上也就是一个http请求,将数据通过xml文件进行交换.
既然知道了原理我们就可以模拟一个http请求来调用webservice.
Java代码 复制代码  收藏代码
  1. try{   
  2.               
  3.            String url2 = "http://192.168.1.1:9010/ZySearch?wsdl";   
  4.   
  5.             URL getUrl = new URL(url2);   
  6.   
  7.             HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();   
  8.             connection.setDoOutput(true);   
  9.             connection.setDoInput(true);   
  10.             connection.setRequestMethod("POST");   
  11.             connection.setRequestProperty("Content-type","text/xml");   
  12.                
  13.                  
  14.             connection.setRequestProperty("Accept","text/xml");   
  15.             connection.setRequestProperty("User-Agent","JAX-WS RI 2.1.3-hudson-390-");   
  16.   
  17.             String send="<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soap:Body><ns1:getUserLink xmlns:ns1=\"http://www.hua-xia.com.cn/ZySearch\"><linkNo xmlns=\"\">"+par+"</linkNo></ns1:getUserLink></soap:Body></soap:Envelope>";   
  18.             connection.getOutputStream().write(send.getBytes());   
  19.             connection.getOutputStream().flush();   
  20.             connection.getOutputStream().close();   
  21.             connection.connect();   
  22.             // 取得输入流,并使用Reader读取   
  23.             BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));//设置编码,否则中文乱码   
  24.             System.out.println("=============================");   
  25.             System.out.println("Contents of get request");   
  26.             System.out.println("=============================");   
  27.             String lines="";   
  28.             String reuslts = "";   
  29.             while ((lines = reader.readLine()) != null){   
  30.                     //lines = new String(lines.getBhqytes(), "utf-8");   
  31.                reuslts+=lines.replaceAll("&lt;""<").replaceAll("&gt;"">");   
  32.                   
  33.             }   
  34.             reader.close();   
  35.                
  36.                
  37.                
  38.             System.out.println("type:"+connection.getContentType());   
  39.             // 断开连接   
  40.             connection.disconnect();   
  41.                
  42.             System.out.println(reuslts);   
  43.             System.out.println("=============================");   
  44.             System.out.println("Contents of get request ends");   
  45.             System.out.println("=============================");   
  46.                
  47.             XStream xStream = new XStream(new DomDriver());   
  48.                
  49.             reuslts = reuslts.substring(reuslts.indexOf("<returnVal>")+11);   
  50.                
  51.             reuslts = reuslts.substring(0,reuslts.indexOf("</returnVal>"));   
  52.                
  53.             System.out.println(reuslts);   
  54.                
  55.             Map result =  (Map)xStream.fromXML(reuslts);   
  56.                
  57.             Iterator it = result.entrySet().iterator();   
  58.                
  59.                while(it.hasNext()){   
  60.                    
  61.                 Map.Entry enty = (Entry) it.next();   
  62.                    
  63.                 System.out.println(enty.getKey()+":"+enty.getValue());   
  64.                    
  65.               }   
  66.               
  67.         }catch(Exception e){   
  68.               
  69.            e.printStackTrace();   
  70.         }  
try{
     	   
     	   String url2 = "http://192.168.1.1:9010/ZySearch?wsdl";

            URL getUrl = new URL(url2);

            HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-type","text/xml");
            
              
            connection.setRequestProperty("Accept","text/xml");
            connection.setRequestProperty("User-Agent","JAX-WS RI 2.1.3-hudson-390-");

            String send="<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soap:Body><ns1:getUserLink xmlns:ns1=\"http://www.hua-xia.com.cn/ZySearch\"><linkNo xmlns=\"\">"+par+"</linkNo></ns1:getUserLink></soap:Body></soap:Envelope>";
            connection.getOutputStream().write(send.getBytes());
            connection.getOutputStream().flush();
            connection.getOutputStream().close();
            connection.connect();
            // 取得输入流,并使用Reader读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));//设置编码,否则中文乱码
            System.out.println("=============================");
            System.out.println("Contents of get request");
            System.out.println("=============================");
            String lines="";
            String reuslts = "";
            while ((lines = reader.readLine()) != null){
                    //lines = new String(lines.getBhqytes(), "utf-8");
         	   reuslts+=lines.replaceAll("&lt;", "<").replaceAll("&gt;", ">");
               
            }
            reader.close();
            
            
            
            System.out.println("type:"+connection.getContentType());
            // 断开连接
            connection.disconnect();
            
            System.out.println(reuslts);
            System.out.println("=============================");
            System.out.println("Contents of get request ends");
            System.out.println("=============================");
            
            XStream xStream = new XStream(new DomDriver());
            
            reuslts = reuslts.substring(reuslts.indexOf("<returnVal>")+11);
            
            reuslts = reuslts.substring(0,reuslts.indexOf("</returnVal>"));
            
            System.out.println(reuslts);
            
            Map result =  (Map)xStream.fromXML(reuslts);
            
            Iterator it = result.entrySet().iterator();
    		
    		   while(it.hasNext()){
    			
    			Map.Entry enty = (Entry) it.next();
    			
    			System.out.println(enty.getKey()+":"+enty.getValue());
    			
    		  }
     	   
        }catch(Exception e){
     	   
     	   e.printStackTrace();
        }





上面的参数send可以在使用jax-ws客户端发送请求的时候,使用sniff工具截取,然后仿造自己构造一个.使用这种方式客户忽略service是何种方式,对于任何webservice都可以实现调用,只是麻烦了一点,但是在无路可走的情况下,也不失为一种选择!

4.jax-ws调用

最后再写上一个jax-ws的client代码

Java代码 复制代码  收藏代码
  1. import java.net.MalformedURLException;   
  2. import java.util.Map;   
  3.   
  4. import javax.xml.namespace.QName;   
  5. import javax.xml.soap.MessageFactory;   
  6. import javax.xml.soap.SOAPBody;   
  7. import javax.xml.soap.SOAPBodyElement;   
  8. import javax.xml.soap.SOAPElement;   
  9. import javax.xml.soap.SOAPMessage;   
  10. import javax.xml.ws.BindingProvider;   
  11. import javax.xml.ws.Dispatch;   
  12. import javax.xml.ws.Service;   
  13. import javax.xml.ws.WebServiceException;   
  14. import javax.xml.ws.soap.SOAPBinding;   
  15.   
  16.   
  17. public class Client {   
  18.     // 名字空间    
  19.     public static final String targetNamespace = "http://www.hua-xia.com.cn/ZySearch";   
  20.     //服务名   
  21.     public static final String serName = "UserLinkWebServiceService";   
  22.     //端口名   
  23.     public static final String pName = "UserLinkWebServicePort";   
  24.     //服务地址   
  25.     public static final String endpointAddress = "http://192.168.1.1:9010/ZySearch?wsdl";   
  26.     //方法名   
  27.     public static final String OPER_NAME = "getUserLink";   
  28.     //参数名   
  29.     public static final String INPUT_NMAE = "linkNo";   
  30.     /**  
  31.      * @param args  
  32.      * @throws MalformedURLException   
  33.      * @throws Exception   
  34.      */  
  35.     public static void main(String[] args) throws MalformedURLException, Exception {   
  36.         // TODO Auto-generated method stub   
  37.   
  38.         QName serviceName = new QName(targetNamespace, serName);   
  39.               
  40.         QName portName = new QName(targetNamespace, pName);   
  41.           
  42.         javax.xml.ws.Service service = Service.create(serviceName);   
  43.         service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);   
  44.           
  45.         Dispatch<SOAPMessage> dispatch = service.createDispatch(portName,   
  46.         SOAPMessage.class, Service.Mode.MESSAGE);   
  47.          
  48.         BindingProvider bp = (BindingProvider) dispatch;   
  49.         Map<String, Object> rc = bp.getRequestContext();   
  50.         rc.put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);   
  51.         rc.put(BindingProvider.SOAPACTION_URI_PROPERTY, OPER_NAME);   
  52.         MessageFactory factory = ((SOAPBinding)bp.getBinding()).getMessageFactory();   
  53.           
  54.         SOAPMessage request = factory.createMessage();   
  55.         SOAPBody body = request.getSOAPBody();   
  56.         QName payloadName = new QName(targetNamespace, OPER_NAME, "ns1");   
  57.         SOAPBodyElement payload = body.addBodyElement(payloadName);   
  58.           
  59.         SOAPElement message = payload.addChildElement(INPUT_NMAE);   
  60.         message.addTextNode("AD0006526305");   
  61.         SOAPMessage reply = null;   
  62.            
  63.         try  
  64.         {   
  65.            reply = dispatch.invoke(request);   
  66.         }   
  67.         catch (WebServiceException wse)   
  68.         {   
  69.            wse.printStackTrace();   
  70.         }   
  71.         SOAPBody soapBody = reply.getSOAPBody();   
  72.         SOAPBodyElement nextSoapBodyElement = (SOAPBodyElement)soapBody.getChildElements().next ();                 
  73.         SOAPElement soapElement = (SOAPElement)nextSoapBodyElement.getChildElements().next();   
  74.      
  75.         System.out.println("获取回应信息为:" + soapElement.getValue());     
  76.        
  77.     }   
  78.   
  79. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值