草庐IT

Java调用wsdl接口的两种方法,axis和wsimport

文明冲浪 2023-04-25 原文

一、AXIS调用远程WebService,以国内手机号归属地查询为例 

1、wsdl地址:http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl

2、导入依赖:

使用axis远程调用webService需要使用到axis、jaxrpc-api、commons-logging、commons-discovery等jar包。方便起见可以新建maven项目,在pom中导入依赖

    <dependencies>
        <dependency>
            <groupId>org.apache.axis</groupId>
            <artifactId>axis</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-discovery</groupId>
            <artifactId>commons-discovery</artifactId>
            <version>0.5</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.axis</groupId>
            <artifactId>axis-jaxrpc</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.axis</groupId>
            <artifactId>axis-saaj</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>wsdl4j</groupId>
            <artifactId>wsdl4j</artifactId>
            <version>1.6.3</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
    </dependencies>

3、调用有入参的webservice接口

阅读wsdl文件,我们可以了解方法名、参数和返回类型

<wsdl:operation name="getMobileCodeInfo">
<wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"><br /><h3>获得国内手机号码归属地省份、地区和手机卡类型信息</h3><p>输入参数:mobileCode = 字符串(手机号码,最少前7位数字),userID = 字符串(商业用户ID) 免费用户为空字符串;返回数据:字符串(手机号码:省份 城市 手机卡类型)。</p><br /></wsdl:documentation>
<wsdl:input message="tns:getMobileCodeInfoSoapIn"/>
<wsdl:output message="tns:getMobileCodeInfoSoapOut"/>
</wsdl:operation>

方法名为:getMobileCodeInfo

参数有两个:mobileCode手机号码,字符串类型;userID用户id,字符串类型(可以为空)

返回类型为字符串

Java调用代码

public static void getMobileCodeInfo() throws ServiceException, RemoteException {
    Service service = new Service();
    Call call = (Call) service.createCall();
    // wsdl完整地址
    call.setTargetEndpointAddress("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl");
    /**
     * 设置方法名
     * new QName(String namespaceURI, String localPart) namespaceURI即为wsdl中的targetNamespace, localPart即为接口名
     */
    call.setOperationName(new QName("http://WebXml.com.cn/", "getMobileCodeInfo"));
    /**
     * 添加参数
     * addParameter方法的参数包括:参数名(namespace+参数名)、参数类型、ParameterMode(入参即为IN)
     */
    call.addParameter(new QName("http://WebXml.com.cn/", "mobileCode"), XMLType.XSD_STRING, ParameterMode.IN);
    call.setUseSOAPAction(true);
    // SOAPActionURI格式为targetNamespace+方法名
    call.setSOAPActionURI("http://WebXml.com.cn/getMobileCodeInfo");
    // 指定返回值类型,为字符串
    call.setReturnType(XMLType.XSD_STRING);
    call.setReturnClass(java.lang.String.class);
    String result = (String) call.invoke(new Object[]{"手机号码"});
    System.out.println(result);
}

4、调用无参的webservice接口

调用无参的webservice接口无需添加参数,并且在invoke方法中传入的是一个空的对象数组

T result = (T)call.invoke(new Object[]{});

 阅读wsdl文件,了解方法名、参数和返回类型

<wsdl:operation name="getDatabaseInfo">
<wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"><br /><h3>获得国内手机号码归属地数据库信息</h3><p>输入参数:无;返回数据:一维字符串数组(省份 城市 记录数量)。</p><br /></wsdl:documentation>
<wsdl:input message="tns:getDatabaseInfoSoapIn"/>
<wsdl:output message="tns:getDatabaseInfoSoapOut"/>
</wsdl:operation>

方法名:getDatabaseInfo,参数:无,返回类型:一维字符串数组

Java调用代码

public static void getDatabaseInfo() throws ServiceException, RemoteException {
    Service service = new Service();
    Call call = (Call) service.createCall();
    call.setTargetEndpointAddress("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl");   //?wsdl
    call.setOperationName(new QName("http://WebXml.com.cn/", "getDatabaseInfo"));
    call.setUseSOAPAction(true);
    call.setSOAPActionURI("http://WebXml.com.cn/getDatabaseInfo");
    call.setReturnType(XMLType.XSD_UNSIGNEDBYTE);
    call.setReturnClass(java.lang.String[].class);
    String[] returnContext = (String[]) call.invoke(new Object[]{});
    for (String s : returnContext) {
        System.out.println(s);
    }
}

二、使用wsimport方法将wsdl转换为Java接口

wsimport命令是JDK自带的命令,它能够根据服务端说明书(wsdl)生成对应的本地java代码。这种方法相较于第一种要简单很多,不用阅读wsdl文件。

wsimport -d <生成.class文件的目录> -s <生成.java文件的目录> -p<包名> <wsdl地址>

 在D:\wsdl下新建文件夹class用于存放.class文件,文件夹java用于存放.java文件

D:\wsdl>wsimport -d class -s java -p mobileCode http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl

执行命令,生成java代码 

 将Java文件拷贝至原先项目中

 Java代码示例

import mobileCode.MobileCodeWS;
import mobileCode.MobileCodeWSSoap;

import java.util.List;

public class Main {
    public static void main(String[] args) {
        MobileCodeWS mobileCodeWS = new MobileCodeWS();
        MobileCodeWSSoap soap = mobileCodeWS.getMobileCodeWSSoap();
        String mobileCodeInfo = soap.getMobileCodeInfo("手机号码", null);
        System.out.println(mobileCodeInfo);
        List<String> dbInfo = soap.getDatabaseInfo().getString();
        System.out.println(dbInfo);
    }
}

wsimport生成的Java代码中自定义了一个ArrayOfString数据结构,用于接收webservice返回的字符串数组,用getString()方法可以将之转化为列表

package mobileCode;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfString", propOrder = {
    "string"
})
public class ArrayOfString {

    @XmlElement(nillable = true)
    protected List<String> string;

    public List<String> getString() {
        if (string == null) {
            string = new ArrayList<String>();
        }
        return this.string;
    }

}

有关Java调用wsdl接口的两种方法,axis和wsimport的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  8. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  9. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

  10. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

随机推荐