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(实例:调用天气预报服务)

  • 相关阅读:
    iOS 字符串遍历
    ImageView通过matrix实现手势缩放,放大,缩小 ,移动
    Xcode 清理存储空间
    iOS学习之字符串(NSString)的截取、匹配、分隔
    convertRect:toView: 和 convertRect:fromView:方法浅析
    社区团购很火爆,影响到小城市菜市场水果店的生意了
    工业级推荐系统 思维导图
    RecBole推荐系统思维导图
    Flink + 强化学习搭建实时推荐系统 思维导图
    传统开源推荐系统介绍思维导图
  • 原文地址:https://www.cnblogs.com/xwz0528/p/4719916.html
Copyright © 2011-2022 走看看