webservice学习1

WebService的特点
WebService通过HTTP POST方式接受客户的请求
WebService与客户端之间一般使用SOAP协议传输XML数据

它本身就是为了跨平台或跨语言而设计的


SOAP(Simple Object Access Protocol):简单对象访问协议

SOAP作为一个基于XML语言的协议用于在网上传输数据。
SOAP = 在HTTP的基础上+XML数据。
SOAP是基于HTTP的。
SOAP的组成如下:
Envelope – 必须的部分。以XML的根元素出现。
Headers – 可选的。
Body – 必须的。在body部分,包含要执行的服务器的方法。和发送到服务器的数据。

例如:

POST /WebServices/IpAddressSearchWebService.asmx HTTP/1.1
Host: ws.webxml.com.cn
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://WebXml.com.cn/getCountryCityByIp"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <getCountryCityByIp xmlns="http://WebXml.com.cn/">
      <theIpAddress>string</theIpAddress>
    </getCountryCityByIp>
  </soap:Body>
</soap:Envelope>

WSDL Web服务描述语言

WSDL(WebService Description Language):web 服务描述语言

就是一个xml文档,用于描述当前服务的一些信息(服务名称、服务的发布地址、服务提供的方法、方法的参数类型、方法的返回值类型等)

使用java代码发布一个webservice服务

@WebService
public class HelloService {

    public String sayHello(String name){

        System.out.println("服务端sayHello方法被调用了!");
        return "hello:" + name;
    }

    public int getAge(){
        System.out.println("服务端getAge方法被调用了!");
        return 18;
    }

    public static void main(String[] args){

        // 使用jdk 发布webservice服务
        String address = "http://192.168.1.119:8080/hello";
        Object implementor = new HelloService();
        Endpoint.publish(address,implementor);

    }
}


在浏览器中访问:http://192.168.1.119:8080/hello?wsdl  ,可以看到wsdl


service name="HelloServiceService" 代表暴露出的服务 , address 是服务的地址

operation name="sayHello" , operation name="getAge"代表方法。


访问http://192.168.1.119:8080/hello?xsd=1


可以看到这两个方法的传入参数类型以及返回值类型。

使用java代码远程调用服务

首先使用jdk自带的命令,根据wsdl生成java代码



将java文件复制到项目中,调用 服务

/**
 * 1、使用wsimport命令解析wsdl文件生成本地代码
 * 2、通过本地代码创建一个代理对象
 * 3、通过代理对象实现远程调用
 */
public class App {

    public static void main(String[] args){

        HelloServiceService helloServiceService = new HelloServiceService();
        HelloService proxy = helloServiceService.getHelloServicePort();
        System.out.println(proxy.sayHello("小明"));
        System.out.println(proxy.getAge());
    }
}

客户端console:

服务端console:


猜你喜欢

转载自blog.csdn.net/LittleGregory/article/details/80384349