zoukankan      html  css  js  c++  java
  • Java实现与调用Web Service

    Web Service

    1. web service

    就是应用程序之间跨语言的调用

    例如,天气预报Web Service:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

    2. wsdl: web service description language(web服务描述语言)

    通过xml格式说明调用的地址方法如何调用,可以看作webservice的说明书

    例如,天气预报的:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl

    3. soap: simple object access protocol(简单对象访问协议)

    soap 在http(因为有请求体,所以必须是post请求)的基础上传输xml数据
    请求和响应的xml 的格式如:

    <Envelop>
        <body>
         //....
        </body>
    </Envelop>

    Java实现与调用Web Service

    1. 目前来讲比较有名的webservice框架大致有四种JWS,Axis,XFire以及CXF。(服务端发布,客户端调用)

    具体可以参考:JWS-webservice 与Axis2-webservice的快速实现

    2. 通过URL Connection调用Webservice(客户端调用,这种方法太麻烦)

    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    /**
     * 通过UrlConnection调用Webservice服务
     *
     */
    public class App {
    
        public static void main(String[] args) throws Exception {
            //服务的地址
            URL wsUrl = new URL("http://192.168.1.100:6789/hello");
            
            HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();
            
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            
            OutputStream os = conn.getOutputStream();
            
            //请求体
            String soap = "<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://ws.itcast.cn/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">" + 
                          "<soapenv:Body> <q0:sayHello><arg0>aaa</arg0>  </q0:sayHello> </soapenv:Body> </soapenv:Envelope>";
            
            os.write(soap.getBytes());
            
            InputStream is = conn.getInputStream();
            
            byte[] b = new byte[1024];
            int len = 0;
            String s = "";
            while((len = is.read(b)) != -1){
                String ss = new String(b,0,len,"UTF-8");
                s += ss;
            }
            System.out.println(s);
            
            is.close();
            os.close();
            conn.disconnect();
        }
    }

    3. 使用ksoap2 调用 WebService(客户端调用)

    主要用于资源受限制的Java环境如Applets或J2ME应用程序以及Android等等(CLDC/ CDC/MIDP)。

    具体可以参考:使用ksoap2 调用 WebService(实例:调用天气预报服务)

  • 相关阅读:
    这个帖子主要总结数据库备份方面的问题
    Visual C#.Net 网络程序开发Socket篇
    数据库设计说明书参考模板
    用Visual C#开发WinForm的应用程序
    在ASP.NET页中读取文本文件
    如何通过 SQL Server 链接服务器和分布式查询使用 Excel
    ER概念模型
    SQL Server 存储过程的分页方案比拼
    读出某一个目录的文件和文件夹
    Linux中的定时任务简单操作实例
  • 原文地址:https://www.cnblogs.com/xwz0528/p/4719916.html
Copyright © 2011-2022 走看看