首页 > 编程语言 > 详细

java调用webservice的四种方式

时间:2015-01-14 02:05:05      阅读:368      评论:0      收藏:0      [点我收藏+]

JAVA SpringMVC+mybatis(oracle 和 mysql) HTML5 全新高大尚后台框架 bootstrap

webservice:
?? ?就是应用程序之间跨语言的调用
?? ?wwww.webxml.com.cn
?? ?1.xml
?? ?2.?? ?wsdl: webservice description language web服务描述语言
?? ??? ?通过xml格式说明调用的地址方法如何调用,可以看错webservice的说明书
?? ?
?? ?3.soap simple object access protoacl (简单对象访问协议)
?? ??? ?限定了xml的格式
?? ??? ?soap 在http(因为有请求体,所以必须是post请求)的基础上传输xml数据
?? ??? ??? ?请求和响应的xml 的格式如:?? ?<Envelop>
?? ??? ??? ??? ??? ??? ??? ??? ?<body>
?? ??? ??? ??? ??? ??? ??? ??? ?//....
?? ??? ??? ??? ??? ??? ??? ??? ?</body>
?? ??? ??? ??? ??? ??? ??? ?</Envelop>
?? ??? ??? ??? ?operation name:服务提供的方法
?? ??? ??? ??? ?
?? ??? ?
?? ?静态方法不能发布为外部服务
?? ?
?? ?运用jkd自带的代码生成访问服务器的客户端代码?? ?E:/wsimort -s . http://test.cm/?wsdl
?? ?
?? ?我们可以把webservice看做是web服务器上的一个应用,web服务器是webservice的一个容器
?? ?
?? ?函数的参数在 http://test.cm/?xsd=1
?? ?
?? ?JAX-WS是指 java api for xml -WebService
?? ?
?? ?//测试 WebService服务的 explorer
?? ?Web Service Explorer 可以显示返回的xml格式
?? ?
?? ?targetNamespace 默认为倒置的包名
?? ?
客户端调用WebService的方式:
?? ?1.通过wximport生成代码
?? ?2.通过客户端编程方式
?? ?3.通过ajax调用方式
?? ?4.通过 URL Connection 方式调用


请求过程分析:
?? ??? ?1.使用get方式获取wsdl文件,称为握手
?? ??? ?2.使用post发出请求

?? ??? ?3.服务器响应成功过

bubuko.com,布布扣

几种监听工具:
?? ?http watch
?? ?Web Service explorer
?? ?eclipse 自带工具?? TCP/IP Monitor


??服务端代码:

?

  1. <span?style="font-size:18px;">package?com.webservcie;??
  2. ??
  3. import?javax.jws.WebMethod;??
  4. import?javax.jws.WebParam;??
  5. import?javax.jws.WebResult;??
  6. import?javax.jws.WebService;??
  7. import?javax.xml.ws.Endpoint;??
  8. ??
  9. /**?
  10. ?*?WebService?
  11. ?*?将?Java?类标记为实现?Web?Service,或者将?Java?接口标记为定义?Web?Service?接口?
  12. ?*/??
  13. @WebService(serviceName="MyService",targetNamespace="http://www.baidu.com")??
  14. public?class?HelloService?{??
  15. ??????
  16. ????@WebMethod(operationName="AliassayHello")??
  17. ????@WebResult(name="myReturn")??
  18. ????public?String?sayHello(@WebParam(name="name")?String?name){??
  19. ????????return??"hello:?"?+?name;??
  20. ????}??
  21. ??????
  22. ????public?String?sayGoodbye(String?name){??
  23. ??????
  24. ????????return??"goodbye:?"?+?name;??
  25. ????}??
  26. ??????
  27. ????@WebMethod(exclude=true)//当前方法不被发布出去??
  28. ????public?String?sayHello2(String?name){??
  29. ????????return?"hello?"?+?name;??
  30. ????}??
  31. ??
  32. ????public?static?void?main(String[]?args)?{??
  33. ????????/**?
  34. ?????????*?参数1:服务的发布地址?
  35. ?????????*?参数2:服务的实现者?
  36. ?????????*??Endpoint??会重新启动一个线程?
  37. ?????????*/??
  38. ????????Endpoint.publish("http://test.cm/",?new?HelloService());??
  39. ????????System.out.println("Server?ready...");??
  40. ????}??
  41. ??
  42. }</span>??
<span style="font-size:18px;">package com.webservcie;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;

/**
 * WebService
 * 将 Java 类标记为实现 Web Service,或者将 Java 接口标记为定义 Web Service 接口
 */
@WebService(serviceName="MyService",targetNamespace="http://www.baidu.com")
public class HelloService {
    
    @WebMethod(operationName="AliassayHello")
    @WebResult(name="myReturn")
    public String sayHello(@WebParam(name="name") String name){
        return  "hello: " + name;
    }
    
    public String sayGoodbye(String name){
    
        return  "goodbye: " + name;
    }
    
    @WebMethod(exclude=true)//当前方法不被发布出去
    public String sayHello2(String name){
        return "hello " + name;
    }

    public static void main(String[] args) {
        /**
         * 参数1:服务的发布地址
         * 参数2:服务的实现者
         *  Endpoint  会重新启动一个线程
         */
        Endpoint.publish("http://test.cm/", new HelloService());
        System.out.println("Server ready...");
    }

}</span>

JAVA SpringMVC+mybatis(oracle 和 mysql) HTML5 全新高大尚后台框架 bootstrap
1.客户端调用(wximport自动生成代码 【推荐】)

?

?

  1. <span?style="font-size:18px;">package?com.wsclient;??
  2. ??
  3. public?class?App?{??
  4. ??
  5. ????/**?
  6. ?????*?通过wsimport?解析wsdl生成客户端代码调用WebService服务?
  7. ?????*??
  8. ?????*?@param?args?
  9. ?????*??
  10. ?????*/??
  11. ????public?static?void?main(String[]?args)?{??
  12. ????????//?TODO?Auto-generated?method?stub??
  13. ??????????
  14. ????????/**?
  15. ?????????*?<service?name="MyService">?
  16. ?????????*?获得服务名称?
  17. ?????????*/??
  18. ????????MyService?mywebService?=?new?MyService();??
  19. ??????????
  20. ????????/**?
  21. ?????????*?<port?name="HelloServicePort"?binding="tns:HelloServicePortBinding">?
  22. ?????????*/??
  23. ????????HelloService?hs?=?mywebService.getHelloServicePort();??
  24. ??????????
  25. ????????/**?
  26. ?????????*?调用方法?
  27. ?????????*/??
  28. ????????System.out.println(hs.sayGoodbye("sjk"));??
  29. ??????????
  30. ????????System.out.println(hs.aliassayHello("sjk"));??
  31. ??????????
  32. ??????????
  33. ??????????
  34. ????}??
  35. ??
  36. }</span>??
<span style="font-size:18px;">package com.wsclient;

public class App {

    /**
     * 通过wsimport 解析wsdl生成客户端代码调用WebService服务
     * 
     * @param args
     * 
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        /**
         * <service name="MyService">
         * 获得服务名称
         */
        MyService mywebService = new MyService();
        
        /**
         * <port name="HelloServicePort" binding="tns:HelloServicePortBinding">
         */
        HelloService hs = mywebService.getHelloServicePort();
        
        /**
         * 调用方法
         */
        System.out.println(hs.sayGoodbye("sjk"));
        
        System.out.println(hs.aliassayHello("sjk"));
        
        
        
    }

}</span>

?2.通过ajax+js+xml调用

?

?

  1. <html>??
  2. ????<head>??
  3. ????????<title>通过ajax调用WebService服务</title>??
  4. ????????<script>??
  5. ??????????????
  6. ????????????var?xhr?=?new?ActiveXObject("Microsoft.XMLHTTP");??
  7. ????????????function?sendMsg(){??
  8. ????????????????var?name?=?document.getElementById(‘name‘).value;??
  9. ????????????????//服务的地址??
  10. ????????????????var?wsUrl?=?‘http://192.168.1.100:6789/hello‘;??
  11. ??????????????????
  12. ????????????????//请求体??
  13. ????????????????var?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">‘?+???
  14. ?????????????????????????????????????‘?<soapenv:Body>?<q0:sayHello><arg0>‘+name+‘</arg0>??</q0:sayHello>?</soapenv:Body>?</soapenv:Envelope>‘;??
  15. ???????????????????????????????????????
  16. ????????????????//打开连接??
  17. ????????????????xhr.open(‘POST‘,wsUrl,true);??
  18. ??????????????????
  19. ????????????????//重新设置请求头??
  20. ????????????????xhr.setRequestHeader("Content-Type","text/xml;charset=UTF-8");??
  21. ??????????????????
  22. ????????????????//设置回调函数??
  23. ????????????????xhr.onreadystatechange?=?_back;??
  24. ??????????????????
  25. ????????????????//发送请求??
  26. ????????????????xhr.send(soap);??
  27. ????????????}??
  28. ??????????????
  29. ????????????function?_back(){??
  30. ????????????????if(xhr.readyState?==?4){??
  31. ????????????????????if(xhr.status?==?200){??
  32. ????????????????????????????//alert(‘调用Webservice成功了‘);??
  33. ????????????????????????????var?ret?=?xhr.responseXML;??
  34. ????????????????????????????var?msg?=?ret.getElementsByTagName(‘return‘)[0];??
  35. ????????????????????????????document.getElementById(‘showInfo‘).innerHTML?=?msg.text;??
  36. ????????????????????????????//alert(msg.text);??
  37. ????????????????????????}??
  38. ????????????????}??
  39. ????????????}??
  40. ????????</script>??
  41. ????</head>??
  42. ????<body>??
  43. ????????????<input?type="button"?value="发送SOAP请求"?onclick="sendMsg();">??
  44. ????????????<input?type="text"?id="name">??
  45. ????????????<div?id="showInfo">??
  46. ????????????</div>??
  47. ????</body>??
  48. </html>??
<html>
    <head>
        <title>通过ajax调用WebService服务</title>
        <script>
            
            var xhr = new ActiveXObject("Microsoft.XMLHTTP");
            function sendMsg(){
                var name = document.getElementById(‘name‘).value;
                //服务的地址
                var wsUrl = ‘http://192.168.1.100:6789/hello‘;
                
                //请求体
                var 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>‘+name+‘</arg0>  </q0:sayHello> </soapenv:Body> </soapenv:Envelope>‘;
                                     
                //打开连接
                xhr.open(‘POST‘,wsUrl,true);
                
                //重新设置请求头
                xhr.setRequestHeader("Content-Type","text/xml;charset=UTF-8");
                
                //设置回调函数
                xhr.onreadystatechange = _back;
                
                //发送请求
                xhr.send(soap);
            }
            
            function _back(){
                if(xhr.readyState == 4){
                    if(xhr.status == 200){
                            //alert(‘调用Webservice成功了‘);
                            var ret = xhr.responseXML;
                            var msg = ret.getElementsByTagName(‘return‘)[0];
                            document.getElementById(‘showInfo‘).innerHTML = msg.text;
                            //alert(msg.text);
                        }
                }
            }
        </script>
    </head>
    <body>
            <input type="button" value="发送SOAP请求" onclick="sendMsg();">
            <input type="text" id="name">
            <div id="showInfo">
            </div>
    </body>
</html>


3.URL Connection方式

?

?

  1. import?java.io.InputStream;??
  2. import?java.io.OutputStream;??
  3. import?java.net.HttpURLConnection;??
  4. import?java.net.URL;??
  5. /**?
  6. ?*?通过UrlConnection调用Webservice服务?
  7. ?*?
  8. ?*/??
  9. public?class?App?{??
  10. ??
  11. ????public?static?void?main(String[]?args)?throws?Exception?{??
  12. ????????//服务的地址??
  13. ????????URL?wsUrl?=?new?URL("http://192.168.1.100:6789/hello");??
  14. ??????????
  15. ????????HttpURLConnection?conn?=?(HttpURLConnection)?wsUrl.openConnection();??
  16. ??????????
  17. ????????conn.setDoInput(true);??
  18. ????????conn.setDoOutput(true);??
  19. ????????conn.setRequestMethod("POST");??
  20. ????????conn.setRequestProperty("Content-Type",?"text/xml;charset=UTF-8");??
  21. ??????????
  22. ????????OutputStream?os?=?conn.getOutputStream();??
  23. ??????????
  24. ????????//请求体??
  25. ????????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\">"?+???
  26. ??????????????????????"<soapenv:Body>?<q0:sayHello><arg0>aaa</arg0>??</q0:sayHello>?</soapenv:Body>?</soapenv:Envelope>";??
  27. ??????????
  28. ????????os.write(soap.getBytes());??
  29. ??????????
  30. ????????InputStream?is?=?conn.getInputStream();??
  31. ??????????
  32. ????????byte[]?b?=?new?byte[1024];??
  33. ????????int?len?=?0;??
  34. ????????String?s?=?"";??
  35. ????????while((len?=?is.read(b))?!=?-1){??
  36. ????????????String?ss?=?new?String(b,0,len,"UTF-8");??
  37. ????????????s?+=?ss;??
  38. ????????}??
  39. ????????System.out.println(s);??
  40. ??????????
  41. ????????is.close();??
  42. ????????os.close();??
  43. ????????conn.disconnect();??
  44. ????}??
  45. }??
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();
    }
}


4.客户单编程方式(和第一种方式一样)

?

?

  1. //文件名:HelloService.java??
  2. ??
  3. import?javax.jws.WebMethod;??
  4. import?javax.jws.WebParam;??
  5. import?javax.jws.WebResult;??
  6. import?javax.jws.WebService;??
  7. import?javax.xml.bind.annotation.XmlSeeAlso;??
  8. import?javax.xml.ws.RequestWrapper;??
  9. import?javax.xml.ws.ResponseWrapper;??
  10. ??
  11. ??
  12. /**?
  13. ?*?This?class?was?generated?by?the?JAX-WS?RI.?
  14. ?*?JAX-WS?RI?2.1.6?in?JDK?6?
  15. ?*?Generated?source?version:?2.1?
  16. ?*??
  17. ?*/??
  18. @WebService(name?=?"HelloService",?targetNamespace?=?"http://ws.itcast.cn/")??
  19. @XmlSeeAlso({??
  20. ??????
  21. })??
  22. public?interface?HelloService?{??
  23. ??
  24. ??
  25. ????/**?
  26. ?????*??
  27. ?????*?@param?arg0?
  28. ?????*?@return?
  29. ?????*?????returns?java.lang.String?
  30. ?????*/??
  31. ????@WebMethod??
  32. ????@WebResult(targetNamespace?=?"")??
  33. ????@RequestWrapper(localName?=?"sayHello",?targetNamespace?=?"http://ws.itcast.cn/",?className?=?"cn.itcast.ws.client.SayHello")??
  34. ????@ResponseWrapper(localName?=?"sayHelloResponse",?targetNamespace?=?"http://ws.itcast.cn/",?className?=?"cn.itcast.ws.client.SayHelloResponse")??
  35. ????public?String?sayHello(??
  36. ????????@WebParam(name?=?"arg0",?targetNamespace?=?"")??
  37. ????????String?arg0);??
  38. ??
  39. }??
//文件名:HelloService.java

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.6 in JDK 6
 * Generated source version: 2.1
 * 
 */
@WebService(name = "HelloService", targetNamespace = "http://ws.itcast.cn/")
@XmlSeeAlso({
    
})
public interface HelloService {


    /**
     * 
     * @param arg0
     * @return
     *     returns java.lang.String
     */
    @WebMethod
    @WebResult(targetNamespace = "")
    @RequestWrapper(localName = "sayHello", targetNamespace = "http://ws.itcast.cn/", className = "cn.itcast.ws.client.SayHello")
    @ResponseWrapper(localName = "sayHelloResponse", targetNamespace = "http://ws.itcast.cn/", className = "cn.itcast.ws.client.SayHelloResponse")
    public String sayHello(
        @WebParam(name = "arg0", targetNamespace = "")
        String arg0);

}

?

  1. import?java.net.MalformedURLException;??
  2. import?java.net.URL;??
  3. ??
  4. import?javax.xml.namespace.QName;??
  5. import?javax.xml.ws.Service;??
  6. ??
  7. import?cn.itcast.ws.wsimport.HelloService;??
  8. ??
  9. /**?
  10. ?*?通过客户端编程的方式调用Webservice服务?
  11. ?*?
  12. ?*/??
  13. public?class?App?{??
  14. ??
  15. ????public?static?void?main(String[]?args)?throws?Exception?{??
  16. ????????URL?wsdlUrl?=?new?URL("http://192.168.1.100:6789/hello?wsdl");??
  17. ????????Service?s?=?Service.create(wsdlUrl,?new?QName("http://ws.itcast.cn/","HelloServiceService"));??
  18. ????????HelloService?hs?=?s.getPort(new?QName("http://ws.itcast.cn/","HelloServicePort"),?HelloService.class);??
  19. ????????String?ret?=?hs.sayHello("zhangsan");??
  20. ????????System.out.println(ret);??
  21. ????}??
  22. }??

JAVA SpringMVC+mybatis(oracle 和 mysql) HTML5 全新高大尚后台框架 bootstrap

java调用webservice的四种方式

原文:http://qq-25086121.iteye.com/blog/2175626

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!