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依赖: 

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!--axis2 begin-->
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-spring</artifactId>
            <version>${axis2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-transport-http</artifactId>
            <version>${axis2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-transport-local</artifactId>
            <version>${axis2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-xmlbeans</artifactId>
            <version>${axis2.version}</version>
        </dependency>
        <!--axis2 end-->
        <dependency>
			<groupId>org.apache.ant</groupId>
			<artifactId>ant</artifactId>
			<version>1.9.7</version>
		</dependency>
		<dependency>
		    <groupId>org.jdom</groupId>
		    <artifactId>jdom</artifactId>
		    <version>2.0.2</version>
		</dependency>
		<dependency>
		    <groupId>commons-net</groupId>
		    <artifactId>commons-net</artifactId>
		    <version>3.3</version>
		</dependency>
		<dependency>
		    <groupId>javax.mail</groupId>
		    <artifactId>javax.mail-api</artifactId>
		    <version>1.4.7</version>
		</dependency>
		<dependency>
		    <groupId>javax.mail</groupId>
		    <artifactId>mail</artifactId>
		    <version>1.4.7</version>
		</dependency>
		<dependency>
		    <groupId>javax.activation</groupId>
		    <artifactId>activation</artifactId>
		    <version>1.1.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/axis/axis -->
		<dependency>
		    <groupId>axis</groupId>
		    <artifactId>axis</artifactId>
		    <version>1.4</version>
		</dependency>
		
		
  </dependencies>

客户端代码:

(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的方法名称,例如<wsdl:operation name="getMobileCodeInfo">)
            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调用方式,码下来当作学习笔记了

 

 

Java和Axis2作为两种流行的编程语言和网络服务框架,方便开发人员创建和使用Web服务应用程序。在Java应用程序中,调用Web服务的一种有效方式是使用Axis2框架。以下是使用Java Axis2调用Web服务接口的步骤: 首先,你需要创建一个Java项目并添加Axis2依赖项。在Eclipse或其他Java IDE中,你可以右键单击项目并选择“属性”>“Java构建路径”>“库”>“添加外部JAR文件”将Axis2 JAR包添加到项目中。 然后,你需要使用WSDL(Web服务描述语言)文件创建客户端代码。WSDL文件描述了Web服务接口的各个方法及其参数和返回值。Java Axis2提供了一个工具,可以根据WSDL文件自动生成客户端代码。你可以使用cmd命令行窗口,转到Axis2的bin目录并执行以下命令创建客户端代码: wsdl2java -uri <WSDL文件路径> -s -d <输出目录路径> 执行完命令后,生成的客户端代码将保存在指定的输出目录路径中。 最后,在Java应用程序中,你需要创建一个服务客户端对象,使用生成的客户端代码调用Web服务的方法。以下是使用Java Axis2调用Web服务接口的示例: 1.创建服务客户端对象 Service service = new ServiceClient(); 2.创建服务端点对象 EndpointReference endpoint = new EndpointReference(<Web服务的URL>); 3.创建调用操作对象 Options options = new Options(); options.setTo(endpoint); options.setAction(<Web服务的命名空间和操作名称>); 4.调用Web服务的方法 OMElement result = service.invokeBlocking(<Web服务的方法名称>, <Web服务的参数>, <Web服务的参数类型>); 以上步骤可以使Java应用程序成功调用Web服务接口,从而实现Web服务的功能。但在实际应用中,还需要考虑安全性、性能优化等方面的因素。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值