webService调用的N种方式

一、服务器端代码

新建一个web Service Project工程(貌似普通的java工程也可以,这里不太明白各种webService的框架有什么区别),建立如下的类:

 

package com.bobo.server;

import javax.jws.WebService;
import javax.xml.ws.Endpoint;

@WebService
public class HelloServer {
    public static void main(String[] args) {
        Endpoint.publish("http://localhost:9001/hello", new HelloServer());
        System.out.println("server is ready!");
    }
    
    public String sayHello(String name){
        return "hello,"+name;
        
    }
}
webService服务器端代码

 

这里需要注意以下几点:

1)@WebService注释必不可少,其作用在于将类或者接口标注为用于实现WebService的类或者接口

2)EndPoint发布完成后,将会用独立的线程运行,因此main中的方法依旧可以执行

3)@WebService,@WebMethod等注释,可以设置wsdl中的server名称,服务提供的方法名称,参数名称,以及方法是否对外发布等

4)服务器端的发布地址后加上?wsdl即可以访问服务的wsdl文件,这是一个WebService的接口描述文件,客户端只需要读懂该文件,就可以知道相关的服务如何调用,相关服务方法的参数,参数类型,返回值类型各是什么(从下往上找)

 

二、调用WebService的四种方法

这里以获取电话号码归属地的公共服务为例,举例说明调用WebService的多种方法

服务器端的描述参见:

http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL

方法一、wsimport生成客户端代码的方式

和java,javac等命令一样,wsimport是jdk自带的一种方法,将jdk的bin目录加入环境变量后,可以在命令行直接执行

wsimport -s [要生成客户端代码的存储路径] -p [要生成客户端代码的包名,如果不指定,那么默认和服务器端的报名相同],如下所示:

wsimport -s E:\\workspace\\myeclipse_workspace\\TheClient\\src -p com.bobo.client -keep [wsdl的地址]

在命令行运行该命令之后,会发现对应的目录下生成了一系列的类文件,这些类文件封装了soap通信协议相关实现方法(soap底层还是http协议,只不过要求发送的请求体的格式必须是xml格式,并对xml中各个字段的写法进行了一系列的规定);

 

客户端调用服务端代码的实现类如下:

 

package com.bobo.test;
import com.bobo.client.*;
 

public class WsimportTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
         
        MobileCodeWSSoap soap=new MobileCodeWS().getMobileCodeWSSoap();
        String result=soap.getMobileCodeInfo("18146531996", null);
        System.out.println(result);
    
    }

}
Wsimport实现的客户端代码

 

 方法二、ajax请求

鉴于上述手机号码归属地的webService同时也支持get和post,因此把get,post以及soap集中方法都记录在此,上述方法在IE11浏览器中均能正常运行,可是在chrome中则不行;此外jquery的ajax方法发送soap正常运行,但使用原生js则返回415码,也不清楚为什么

关于上述问题的一些想法:前端发送ajax请求到后台,可能会出现跨域情况,

关于跨域,需要注意以下几点:

1)当前端发送ajax请求的主机和后台提供服务的主机不是同一台的时候,如sina.com——>baidu.com的时候,会出现跨域

2)如果前端请求本机的服务,本机有两种表示localhost和ip地址,当两种表示不一样的时候,也会出现跨域,如localhost——>192.168.x.x

3)跨域只有前端发送请求的情况下才可能出现,如果是后台,如java代码发送请求,是不会出现跨域的。

 

/*调用服务的get方法*/
function getResultByGet(){
    $.ajax({
        type:'GET',
        dataType:'xml',
        url:'http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=18146531996&userID=',
        success:function(data){
            alert($(data).find("string").text());             
        }
    });
}
get方式请求接口
/*调用服务的post方法*/
function getResultByPost(){
    //alert("post");
    $.ajax({
        type:'POST',
        dataType:'xml',
        url:'http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo',
        data:{"mobileCode":"18146531996","userID":null},
        success:function(data){
            alert($(data).find("string").text());             
        }
    });
}
post方式请求接口
$(function(){

    
var soapData='<?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>'+
    '<getMobileCodeInfo xmlns="http://WebXml.com.cn/">'+
      '<mobileCode>18146531996</mobileCode>'+
      '<userID></userID>'+
   '</getMobileCodeInfo>'+
  '</soap:Body>'+
'</soap:Envelope>';
    getResultByGet();
    //getResultByPost();
    //getResultByJqueryAjax(soapData);
    //getResultByRawJS(soapData);
});

/*遵从soap协议,利用jquery*/
function getResultByJqueryAjax(soapData){
        alert("soap");
        $.ajax({
        url:'http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx',    
        type:'POST',    
        //content-type:'text/xml;charset=UTF-8',
        dataType:'xml',
        data:soapData,
        beforeSend:function(XmlHttpRequest){
            //下面这句soapAction的设定貌似可有可无,但是Content-Type是必须的
            XmlHttpRequest.setRequestHeader("SOAPAction","http://WebXml.com.cn/getMobileCodeInfo");
            XmlHttpRequest.setRequestHeader("Content-Type","text/xml;charset=utf-8");
        },
        success:function(data){
            alert($(data).find("getMobileCodeInfoResult").text());
        }
        
    });
    
}
soap形式,利用jquery发送ajax请求
/*遵从soap协议,利用原始js*/
function getResultByRawJS(soapData){
    alert("getResultByRawJS");
    var xhr;
    if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xhr=new XMLHttpRequest();
        }        else
        {// code for IE6, IE5
            xhr=new ActiveXObject("Microsoft.XMLHTTP");
        }
    //使用原生的js试一下
    //var xhr=new XMLHttpRequest();
    var url='http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx';
    xhr.open('POST',url,true);
    xhr.setRequestHeader("Content-Type","text-xml;charset=utf-8");          
    xhr.setRequestHeader("SOAPAction","http://WebXml.com.cn/getMobileCodeInfo");     
    xhr.send(soapData);
    xhr.onreadystatechange=_back;
    
    function _back(){         
        if(xhr.readyState==4){         
            if(xhr.status==200){
                alert("xhr.responseText:"+xhr.responseText);
            }
            
        }
        
    };
}
soap方式,利用js发送ajax请求

 

方法三、urlConnection请求

 

package com.bobo.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class UrlConnectionTest {

    public static void main(String[] args) throws Exception {
         

    String data="<?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>"+
           " <getMobileCodeInfo xmlns=\"http://WebXml.com.cn/\">"+
             " <mobileCode>18146531996</mobileCode>"+
              "<userID></userID>"+
           " </getMobileCodeInfo>"+
         " </soap:Body>"+
        "</soap:Envelope>";
    String result=sendPost("http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx",data);
    System.out.println(result);
         
    }
    private static String sendPost(String url,String data) throws Exception{
        StringBuilder result=new StringBuilder();
        URL realUrl=new URL(url);
        URLConnection connection=realUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        connection.setRequestProperty("SOAPAction", "http://WebXml.com.cn/getMobileCodeInfo");
        PrintWriter writer=new PrintWriter(connection.getOutputStream());
        writer.write(data);
        writer.flush();
        writer.close();
        
        BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line="";
        while((line=reader.readLine())!=null){
            result.append(line);
        }
        return result.toString();
    }
}
UrlConnection请求WebService

 

 

 

方法四、request请求

 

 

posted @ 2015-07-09 16:53  bobo的学习笔记  阅读(2995)  评论(0编辑  收藏  举报