ajax、Jquery、HttpUrlConnectin请求web service

ajax请求web service

1、客户端发起请求,会发送一段下面这样的信息,Payload就是通过标签进行数据传递。

ID: 1
Address: http://localhost:8080/wx-cxf-server-spring/orderws
Encoding: UTF-8
Content-Type: text/xml
Headers: {Accept=[*/*], SOAPAction=[""]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><atguigu><name>xfzhang</name><password>123456</password></atguigu></soap:Header><soap:Body><ns2:getOrderById xmlns:ns2="http://spring/"><arg0>24</arg0></ns2:getOrderById></soap:Body></soap:Envelope>

所以在发起ajax请求时,我们需要发送一个这样类型的字符串,通过获取用户在页面填写的数据进行拼接。
ajax示例代码

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.7.2.js"></script>

<script type="text/javascript">
	 function reqWebService() {
	 // 获取文本框输入的值
		var name = document.getElementById("name").value;
	//请求发送的数据
		var data = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:sayHello xmlns:ns2="http://ws.day01_ws.atguigu.com/"><arg0>'+name+'</arg0></ns2:sayHello></soap:Body></soap:Envelope>';
		//1、创建XMLHttpRequest对象
		var request = getRequest();
		//2、设置回调函数
		request.onreadystatechange = function(){
		\\如果成功,获取数据
			if(request.readyState==4 && request.status==200) {
			//获取xml文档格式的数据
				var result = request.responseXML;
				alert(result);
				//获取return标签下的值
				var returnEle = result.getElementsByTagName("return")[0];
				var value = returnEle.firstChild.data;
				alert(value);
			}
		};
		// 3、打开连接
		request.open("POST", "http://192.168.10.165:8888/day01_ws/datatypews");
		// 4、设置一个请求头
		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		// 5、发送请求
		request.send(data);
	}

	function getRequest() {
		var xmlHttp = null;
		try {
			// Firefox, Opera 8.0+, Safari  chrome
			xmlHttp = new XMLHttpRequest();
		} catch (e) {
			// Internet Explorer
			try {
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		return xmlHttp;
	} 
</script>
</head>
<body>
	用户名:
	<input id="name" name="username" value="" />
	<br>
	<button onclick="reqWebService()">AJax请求webservice</button>
</body>
</html>

在前端请求web service后端时,会出现跨域问题。

jquery 请求web service

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">

	$(function(){
		
	
		$("#btn").click(function(){ //回调函数
			var name = document.getElementById("name").value;
			var data = '<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:sayHello xmlns:ns2="http://ws.day01_ws.atguigu.com/"><arg0>'+name+'</arg0></ns2:sayHello></soap:Body></soap:Envelope>';
			
			$.ajax({
				type : "post",
				url : "http://192.168.10.165:8888/day01_ws/datatypews",
				data : data,
				success : function(msg){
					alert("------");
					var $Result = $(msg);
					var value = $Result.find("return").text();
					alert(value);
				},
				error : function(msg) {
					//alert("-----"+msg);
				},
				dataType : "xml"
			});
		});
	});
</script>
</head>
<body>
	用户名:
	<input id="name" name="username" value="" />
	<br>

	<button id="btn">Jquery请求webservice</button>

</body>
</html>

直接使用js向web service会发生跨域请求问题,我们可以先通过页面向本地后端发起请求,然后再由java后端向web service发起请求。

HttpUrlConnection 请求web Service

1、前端模拟

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">

	$(function(){
		
		$("#btn2").click(function(){
			var name = document.getElementById("name").value;
			$.post(
				"HttpURLConnectionServlet",
				"name="+name,
				function(msg) {
					//alert(msg);
					var $Result = $(msg);
					var value = $Result.find("return").text();
					alert(value);
				},
				"xml"
			);
		});
</script>
</head>
<body>
	用户名:
	<input id="name" name="username" value="" />
	<br>

	<button id="btn2">HttpURLConnection请求webservice</button>
	
</body>
</html>

2、创建一个servlet

/**
 * 使用HttpURLConnection发送webservice请求
 */
public class HttpURLConnectionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		System.out.println("doPost "+name);
		
		String data = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><ns2:sayHello xmlns:ns2='http://ws.day01_ws.atguigu.com/'><arg0>"+name+"</arg0></ns2:sayHello></soap:Body></soap:Envelope>";
		//
		URL url = new URL("http://192.168.10.165:8888/day01_ws/datatypews");
		
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		
		connection.setRequestMethod("POST");
		//设置是否可以读写数据
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
		//将数据写到web service 服务器端
		OutputStream os = connection.getOutputStream();
		//将data数据变成byte数组
		os.write(data.getBytes("utf-8"));
		
		int responseCode = connection.getResponseCode();
		//如果响应码为200,从web service服务端读取数据
		if(responseCode==200) {
			InputStream is = connection.getInputStream();//String xml
			System.out.println("return "+is.available());
			
			//将读到的数据,写出到页面。
			response.setContentType("text/xml;charset=utf-8");
			ServletOutputStream outputStream = response.getOutputStream();
			
			byte[] buffer = new byte[1024];
			int len = 0;
			while((len=is.read(buffer))>0) {
				outputStream.write(buffer, 0, len);
			}
			outputStream.flush();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/taojin12/article/details/87862875
今日推荐