WebService 学习之---WebService四种调用方式

一、创建一个简单的WebService服务 (JAX-WS)

在myeclipse上右键创建一个WebService Project


取名为DemoWebService ,采用JAX-WS框架,另一种是JAX-RS框架,不赘述。


然后在src下创建com.jiaox.service包,并创建HelloWS类


然后对HelloWS进行如下编写

package com.jiaox.service;

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

/**
 * 使用  jax-ws框架 编写的service类
 * @author jiaox
 *
 */

@WebService
public class HelloWS {
	/**
	 * 打招呼方法,客户端调用
	 * @param name   姓名
	 * @return  String  返回结果
	 */
	public String sayHello(String name){
		return "hello,我叫:"+name;
	}
	
	public static void main(String[] args) {
		//发布服务端
		Endpoint.publish("http://localhost:9001/WebService/HelloWS", new HelloWS());
		System.out.println("service success!");
		
	}
	
}

运行结果


这时通过浏览器访问 http://localhost:9001/WebService/HelloWS,则出现


点WSDL的URL则可查看WSDL内容


这样一个WebService服务就发布完了。

二、四种调用方式

1. 通过客户端,也就是需要借助wsimport命令创建客户端代码来访问

 创建一个WSClient的WebService Project工程


打开DOS命令窗口,输入如下格式命令

wsimport -s [客户端工程目录\\src] -p [client包名] -keep [wsdl地址]
我本地的例子如下:
wsimport -s D:\\Workspaces\\MyEclipse10\\WSClient\\src -p com.jiaox.client -keep http://localhost:9001/WebService/HelloWS?wsdl

刷新一下工程如下:


在com.jiaox.test包下创建一个测试类ServiceTest,代码如下:

package com.jiaox.test;

import com.jiaox.client.HelloWS;
import com.jiaox.client.HelloWSService;


public class ServiceTest {
	public static void main(String[] args) {
		HelloWS hello=new HelloWSService().getHelloWSPort();
		String name = hello.sayHello("John");
		System.out.println(name);
	}
}

运行结果:


2. 通过Service类实现调用

    不通过wsimport命令生成客户端类,也可以通过wsimport生成,但是只需要其中的一个接口,即与服务器端接口完全相同的类。

所以有如下几点:

1. javax.xml.ws.Service 类,用于访问web服务

2. 与Web服务同名接口类,这个用wsimport生成并拷贝到本地工程。

3.此方式和第一种方式其实原理相同,第一种方式只是将功能封装。

    创建一个工程WSClient2


在com.jiaox.client包中创建一个接口类HelloWS,代码如下:

package com.jiaox.client;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.Action;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;

@WebService(name = "HelloWS", targetNamespace = "http://service.jiaox.com/")
public interface HelloWS {
	/**
	 * 
	 * @param arg0
	 * @return returns java.lang.String
	 */
	@WebMethod
	@WebResult(targetNamespace = "")
	@RequestWrapper(localName = "sayHello", targetNamespace = "http://service.jiaox.com/", className = "com.jiaox.client.SayHello")
	@ResponseWrapper(localName = "sayHelloResponse", targetNamespace = "http://service.jiaox.com/", className = "com.jiaox.client.SayHelloResponse")
	@Action(input = "http://service.jiaox.com/HelloWS/sayHelloRequest", output = "http://service.jiaox.com/HelloWS/sayHelloResponse")
	public String sayHello(
			@WebParam(name = "arg0", targetNamespace = "") String arg0);
}

在com.jiaox.test中创建一个ServiceTest类

package com.jiaox.test;

import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import com.jiaox.client.HelloWS;


public class ServiceTest {
	public static void main(String[] args) throws Exception {
		//创建WSDL的URL,注意不是服务地址  
        URL url = new URL("http://localhost:9001/WebService/HelloWS?wsdl"); 
      //创建服务名称  
        //1.namespaceURI - 命名空间地址  
        //2.localPart - 服务视图名  
        QName qname = new QName("http://service.jiaox.com/", "HelloWSService");
      //创建服务视图  
        //参数解释:  
        //1.wsdlDocumentLocation - wsdl地址  
        //2.serviceName - 服务名称  
        Service service = Service.create(url, qname);  
      //获取服务实现类  
        HelloWS hello = service.getPort(HelloWS.class); 
      //调用查询方法  
        String result = hello.sayHello("JaneAi");  
        System.out.println(result); 
	}
}

运行结果:


3. 通过Ajax调用

在WSClient2中创建一个test.html


代码如下:

<!DOCTYPE html>
<html>
<head>
<title>test.html</title>

<script type="text/javascript">
	function sendAjaxWS() {
		var axobj = new ActiveXObject("Microsoft.XMLHTTP");
		alert(1);
		//指定ws的请求地址

		var wsUrl = "http://localhost:9001/WebService/HelloWS";

		//手动构造请求体
		var requestBody = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" ' + '  xmlns:q0="http://service.jiaox.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema "'
				+' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
				+' <soapenv:Body><q0:sayHello><arg0>'
				+document.getElementById("msg").value
				+' </arg0> <arg1>10</arg1> </q0:sayHello></soapenv:Body></soapenv:Envelope>';

		//打开连接

		axobj.open("POST", wsUrl, true);

		//重新设置请求头       xhr.setRequestHeader("content-type","text/xml;charset=utf8");

		//设置回调函数

		axobj.onreadystatechange = _back;

		//发送请求

		axobj.send(requestBody);
	}
	
	function _back(){  
        
        if(xhr.readyState == 4){  
          
            if( xhr.status == 200 ){  
                /* 有浏览器兼容问题 */  
                var ret = xhr.responseXML;  
                var msg = ret.getElementsByTagName('return')[0];  
                alert(msg);  
                  
            }  
        }  
    }
</script>

</head>

<body>
	<input type="button" οnclick='sendAjaxWS()' value="发送">
	<input type="text" id="msg" name="msg">
</body>
</html>

启动webservice服务,并将WSClient2部署到tomcat中去,运行。


最后成功访问WebService

注意:以上html中的代码因为用到ActiveXObject是只有IE支持的,所以只能在IE上运行。另外用此ajax方式调用必须保证前端和WebService服务是在同一域中,跨域不能访问,可以考虑用ajax调用后台服务,再通过后台访问webservice避免跨域问题。

4.通过URLConnection调用

在WSClient2工程com.jiaox.test 包下新建ServiceTest2类

代码如下:

package com.jiaox.test;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class ServiceTest2 {
	public static void main(String[] args) throws Exception {
		String wsUrl = "http://localhost:9001/WebService/HelloWS";
		URL url = new URL(wsUrl);
		URLConnection conn = url.openConnection();
		HttpURLConnection con = (HttpURLConnection) conn;
		con.setDoInput(true); // 是否有入参

		con.setDoOutput(true); // 是否有出参

		con.setRequestMethod("POST"); // 设置请求方式

		con.setRequestProperty("content-type", "text/xml;charset=UTF-8");
		String requestBody = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "

				+ " xmlns:q0=\"http://service.jiaox.com/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema \" "

				+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"

				+ "<soapenv:Body><q0:sayHello><arg0>lisi</arg0> <arg1>10</arg1> </q0:sayHello></soapenv:Body></soapenv:Envelope>";
		OutputStream out = con.getOutputStream();

        out.write(requestBody.getBytes());

        out.close();
        int code = con.getResponseCode();

        if(code == 200){//服务端返回正常

          InputStream is = con.getInputStream();

          byte[] b = new byte[1024];

          StringBuffer sb = new StringBuffer();

          int len = 0;

          while((len = is.read(b)) != -1){

              String str = new String(b,0,len,"UTF-8");

              sb.append(str);

         }

         System.out.println(sb.toString());

         is.close();

        }
        
        con.disconnect();
        
	}
}

运行结果:


证明调用成功!!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值