java调用webService接口的几种方法

        webservice的 发布一般都是使用WSDL(web service descriptive language)文件的样式来发布的,在WSDL文件里面,包含这个webservice暴露在外面可供使用的接口。

1.可以通过带有webservice插件的Eclipse直接生成调用webservice客户端代码

在Eclipse中生成webservice客户端代码,New---->Other---->Webservice---->Webservice Client,选择之前拷贝到eclipse中的wsdl路径点击finish,这样eclipse就帮我们自动生成了webservice的客户端,接下来只需在程序中调用即可,在程序中调用eclipse自动生成的webservice客户端;

        

生成的客户端代码:

    

测试案例:

 

2.使用axis1.4或2.X生成webservice的客户端代码

1、下载axis1.4,解压; 
2、在axis-1_4目录下新建wsdl2java-client.bat(.bat批处理文件,可任意命名)文件,增加内容如下:

set Axis_Lib=.\lib
set Java_Cmd=java -Djava.ext.dirs=%Axis_Lib%
%Java_Cmd% org.apache.axis.wsdl.WSDL2Java   -p com.lmb.client.ws C:\Users\Administrator\Desktop\axis-1_4\axis-1_4\lmbtest.xml
pause

注意:其中com.lmb.client.ws为生成的客户端代码的包路径,C:\Users\Administrator\Desktop\axis-1_4\axis-1_4\lmbtest.xml为wsdl文件。

3、双击wsdl2java-client.bat:

可以看到相关路径下生成的客户端代码如下:

4、调用方法如下:

public class WebServiceClientTest{
    public static void main(String[] args){
        String wsdl = "http://xxx.xxx.xx.xx:8082/csp/services/c_lttb/orderToHeLiWebservice";
        String requestStr = "";

        // 有些webservice需要登录,登陆后才能进行一些操作,这个需要设置如下两个参数: 
        //1、 超时时间 
        stub.setTimeout(1000 * 60 * 20); 
        //2、 次数设置true,登录后才能保持登录状态,否则第二次调用ws方法时仍然会提示未登录。 
        stub.setMaintainSession(true);

        org.apache.axis.client.Service service = new org.apache.axis.client.Service();
        OrderToHeLiWebserviceHttpBindingStub stub = new OrderToHeLiWebserviceHttpBindingStub(
            new java.net.URL(wsdl), service);
        String response = stub.urgeWorkOrderServiceSheet(requestStr); //调用ws提供的方法
        System.out.println("response >>> " + response);
    }
}

3.手写客户端代码方式

新建一个maven工程

pom.xml添加jar依赖: 


    
      junit
      junit
      3.8.1
      test
    
    
        
            org.apache.axis2
            axis2-spring
            ${axis2.version}
        
        
            org.apache.axis2
            axis2-transport-http
            ${axis2.version}
        
        
            org.apache.axis2
            axis2-transport-local
            ${axis2.version}
        
        
            org.apache.axis2
            axis2-xmlbeans
            ${axis2.version}
        
        
        
			org.apache.ant
			ant
			1.9.7
		
		
		    org.jdom
		    jdom
		    2.0.2
		
		
		    commons-net
		    commons-net
		    3.3
		
		
		    javax.mail
		    javax.mail-api
		    1.4.7
		
		
		    javax.mail
		    mail
		    1.4.7
		
		
		    javax.activation
		    activation
		    1.1.1
		
		
		
		    axis
		    axis
		    1.4
		
		
		
  

客户端代码:

(1)这里是用axis调用的 我自己写的代码 由于我的服务端接口比较老 所以我采用这种方式成功上传了数据 但是传输的附件大小只能不超过20k,超过了就报系统找不到指定的路径,暂时不知道为什么,希望知道的人告知下

package com.TestWebService.WebService;

import java.io.File;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.xml.namespace.QName;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.ser.JAFDataHandlerDeserializerFactory;
import org.apache.axis.encoding.ser.JAFDataHandlerSerializerFactory;

public class AxisToWebServiceImportData {
	public String invokeByAxis() {
		boolean result = false;
		Service service = new Service();
		String endPoint = "http://192.168.0.***:8080/ESWebService/services/DataInterfaceService";
		try {
		Call call = (Call) service.createCall();
		call.setTargetEndpointAddress(endPoint);

		call.setEncodingStyle("utf-8");
		
		String srcFilePath = "D:\\sip-data.zip";
        String userName = "admin";
        String password = "*****";
        String flk_id = "27";
        String wjm = "wj1327";
        String zipName = "sip-data.zip";
        String encode = "92BBE4B3******067E9E5F17";
        DataHandler dh = new DataHandler(new FileDataSource(srcFilePath));
        
        
        QName qnameattachment = new QName("DataInterfaceService", "DataHandler");
        call.registerTypeMapping(dh.getClass(),qnameattachment,JAFDataHandlerSerializerFactory.class,JAFDataHandlerDeserializerFactory.class);
		call.addParameter("dh", qnameattachment, javax.xml.rpc.ParameterMode.IN);
        call.addParameter("userName", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
		call.addParameter("password", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
		call.addParameter("flk_id", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
		call.addParameter("wjm", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
		call.addParameter("zipName", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
		call.addParameter("encode", org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.IN);
		call.setReturnType(org.apache.axis.encoding.XMLType.XSD_BOOLEAN);
		call.setOperationName(new QName(endPoint,"importData"));

		result = (Boolean) call.invoke(new Object[]{dh,userName,password,flk_id,wjm,zipName,encode});
		System.out.println("返回值:" + result);
		} catch (Exception e) {
		System.out.print("WebService请求异常!! ");
		e.printStackTrace();
		}
		return "true";

	}
	public static void main(String[] args) {
		AxisToWebServiceImportData a = new AxisToWebServiceImportData();
		a.invokeByAxis();
	}
}

(2)第二种方式是用RPC方式调用

package com.TestWebService.WebService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.xml.namespace.QName;

import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.axis2.transport.http.HTTPConstants;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.DOMBuilder;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.DOMOutputter;
import org.jdom2.xpath.XPath;

public class ImportData {
	public boolean TestWebService() {
		boolean result = false;
		
		try {
			RPCServiceClient serviceClient = new RPCServiceClient();
			
			 
            String url = "http://192.168.0.207:8080/ESWebService/services/DataInterfaceService";
            // 指定调用WebService的URL
            EndpointReference targetEPR = new EndpointReference(url);
            Options options = serviceClient.getOptions();
            // 确定目标服务地址
            options.setTo(targetEPR);
            
            // 确定调用方法
            options.setAction("importData");
            
            options.setProperty(HTTPConstants.CHUNKED, "false");// 把chunk关掉后,会自动加上Content-Length
            //解决高并发链接超时问题
            options.setManageSession(true);
            options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT,true);
       
            //设置响应超时,默认5s
            options.setProperty(HTTPConstants.SO_TIMEOUT, 5000);
            //设置连接超时,默认5s
            options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, 5000);

            String srcFilePath = "D:\\sip-data.zip";
            String userName = "admin";
            String password = "*****";
            String flk_id = "27";
            String wjm = "wj1327";
            String zipName = "sip-data.zip";
            String encode = "92BBE4B*****93A067E9E5F17";
            DataHandler dh = new DataHandler(new FileDataSource(new File(srcFilePath)));
            System.out.println("dh:::" + dh);
            // 指定方法的参数值
            Object[] parameters = new Object[] {dh,userName,password,flk_id,wjm,zipName,encode};
            
            // 创建服务名称
            // 1.namespaceURI - 命名空间地址 (wsdl文档中的targetNamespace)
            // 2.localPart - 服务视图名 (wsdl文档中operation的方法名称,例如)
            QName qname = new QName("http://192.168.0.***:8080/ESWebService/services/DataInterfaceService", "importData");
            
            
            // 指定方法返回值的数据类型的Class对象
            Class[] returnTypes = new Class[] {Boolean.class};
            Object[] response = serviceClient.invokeBlocking(qname, parameters,returnTypes);
//            OMElement element = serviceClient.invokeBlocking(qname, parameters);
//            System.out.println("element::" + element);
            /*
             * 值得注意的是,返回结果就是一段由OMElement对象封装的xml字符串。
             * 我们可以对之灵活应用,下面我取第一个元素值,并打印之。因为调用的方法返回一个结果
             */
//            result = element.getFirstElement().getText();
//            System.out.println(result);

            result =   (Boolean) response[0];
            
		} catch (AxisFault e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
		
		return result;
	}
	
	
	public static void main(String[] args) {
		
		ImportData t = new ImportData();
		System.out.println("result:::"+ t.TestWebService());
		
	}
}

(3) 应用document方式调用 用ducument方式应用现对繁琐而灵活,引入相应的axis2的jar包

package com.TestWebService.WebService;

import java.io.File;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.xml.namespace.QName;

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.OMText;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;

public class ImportDataTwo {
	
	public boolean TestImportData() {
		boolean res = false;
		try {
            ServiceClient serviceClient = new ServiceClient();
            //创建服务地址WebService的URL,注意不是WSDL的URL
            String url = "http://192.168.0.207:8080/ESWebService/services/DataInterfaceService";
            EndpointReference targetEPR = new EndpointReference(url);
            Options options = serviceClient.getOptions();
            options.setTo(targetEPR);
            //确定调用方法(wsdl 命名空间地址 (wsdl文档中的targetNamespace) 和 方法名称 的组合)
            options.setAction("http://192.168.0.207:8080/ESWebService/services/DataInterfaceService/importData");

            OMFactory fac = OMAbstractFactory.getOMFactory();
            /*
             * 指定命名空间,参数:
             * uri--即为wsdl文档的targetNamespace,命名空间
             * perfix--可不填
             */
            OMNamespace omNs = fac.createOMNamespace("http://192.168.0.***:8080/ESWebService/services/DataInterfaceService", "");
            // 指定方法
            OMElement method = fac.createOMElement("importData", omNs);
            // 指定方法的参数
            OMElement userName = fac.createOMElement("userName", omNs);
            userName.setText("admin");
            OMElement password = fac.createOMElement("password", omNs);
            password.setText("*****");
            
            String srcFilePath = "D:\\sip-data.zip";
            
            DataHandler dh2 = new DataHandler(new FileDataSource(new File(srcFilePath)));
            OMText textData = fac.createOMText(dh2, true);
            OMElement dh = fac.createOMElement("dh", omNs);
            dh.addChild(textData);
            System.out.println("dh:::" + dh2);
            
            OMElement flk_id = fac.createOMElement("flk_id", omNs);
            flk_id.setText("27");
            
            OMElement wjm = fac.createOMElement("wjm", omNs);
            wjm.setText("wj1327");
            
            OMElement zipName = fac.createOMElement("zipName", omNs);
            zipName.setText("sip-data.zip");
            
            OMElement encode = fac.createOMElement("encode", omNs);
            encode.setText("92BBE4B3BC*****393A067E9E5F17");
            
            
            method.addChild(dh);
            method.addChild(userName);
            method.addChild(password);
            method.addChild(flk_id);
            method.addChild(wjm);
            method.addChild(zipName);
            method.addChild(encode);
           // method.build();
            System.out.println(method);
            //远程调用web服务
            OMElement result = serviceClient.sendReceive(method);
            System.out.println(result);

        } catch (AxisFault axisFault) {
            axisFault.printStackTrace();
        }
    

		
		return true;
	}
	
	public static void main(String[] args) {
		ImportDataTwo t = new ImportDataTwo();
		t.TestImportData();
	}
}

暂时只接触到这么多webservice调用方式,码下来当作学习笔记了

 

 

你可能感兴趣的:(webservice)