您好,欢迎来到尔游网。
搜索
您的当前位置:首页利用JDK开发WebService简单实现

利用JDK开发WebService简单实现

来源:尔游网

①SEI接口:HelloWs.java

package com.service;
/*
 *定义SEI接口,同时定义方法来接受客户端传参并提供返回值给客户端 
 */
import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public interface HelloWs {
    @WebMethod
    public String getValue(String name);
}

注意:@WebService和@WebMethod注解不可省略

②SEI接口实现类:HelloWsImpl.java

package com.service;

import javax.jws.WebService;

/*
 * SEI接口的实现类
 */
@WebService
public class HelloWsImpl implements HelloWs {

    @Override
    public String getValue(String name) {
        System.out.println("服务端调用getValue方法接收客户端传参:"+name);
        return "服务端返回值";
    }

}

③发布webservice:ServerTest.java

package com.test;

import javax.xml.ws.Endpoint;

import com.service.HelloWsImpl;

public class ServerTest {
    public static void main(String[] args) {
        String address="http://localhost:8087/webservice/hello";
        Endpoint.publish(address, new HelloWsImpl());
        System.out.println("webservice发布成功!");
    }
}

运行ServerTest.java,控制台输出:

客户端开发:
首先建立客户端项目WSClient

现在不用改动自动生成的代码,新建一个客户端测试类ClientTest.java
来验证客户端与服务端能否正常交互

package com.test;

import com.service.HelloWsImpl;
import com.service.HelloWsImplService;

public class ClientTest {
    public static void main(String[] args) {
        HelloWsImplService helloWsImplService=new HelloWsImplService();
        HelloWsImpl helloWsImpl= helloWsImplService.getHelloWsImplPort();
        String result=helloWsImpl.getValue("Huge");
        System.out.println("客户端向服务端传参,收到服务端返回值:"+result);
    }
}

启动客户端后:
服务端控制台输出:

大多数情况下,我们并不需要开发服务端,网上有很多可以使用的免费webservice接口。我们不用管服务端是用什么语言怎样开发的,只要知道如何客户端调用该服务端的资源就可以了,这也是webservice的优点之一!跨平台更跨语言!
比如,该网站就提供了很多免费webservice服务。
下面用一个简单的例子演示一下:
手机号码归属地查询
先找到URL(wsdl文件),然后dos命令窗口编译
最后编写客户端测试类

package cn.com.test;

import cn.com.webxml.MobileCodeWS;
import cn.com.webxml.MobileCodeWSSoap;

public class ClientTest {
    public static void main(String[] args) {
        MobileCodeWS mobileCodeWS=new MobileCodeWS();
        MobileCodeWSSoap mobileCodeWSSoap=mobileCodeWS.getMobileCodeWSSoap();
        String result=mobileCodeWSSoap.getMobileCodeInfo("156772745", null);
        System.out.println(result);
    }
}

输出:

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- axer.cn 版权所有 湘ICP备2023022495号-12

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务