使用ajax和urlconnection方式调用webservice服务

<html>
<head>
<title>使用ajax方式调用webservice服务</title>
<script>
var xhr = new XMLHttpRequest();
function sendAjax(){
var url = "http://192.168.13.66:8080/hello";//webservice服务的地址
var requestBody = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" ' + 'xmlns:q0="http://service.demo.cn/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' + 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'+
'<soapenv:Body><q0:sayHi> <arg0>xiaoming</arg0></q0:sayHi></soapenv:Body></soapenv:Envelope>';//构造请求体,符合soap协议规范 //打开连接
xhr.open("POST",url,true); //重新设置请求头
xhr.setRequestHeader("content-type","text/xml;charset=UTF-8"); //指定回调函数
xhr.onreadystatechange = _back; //发送请求
xhr.send(requestBody);
} //定义回调函数
function _back(){
if(xhr.readyState == 4){
if(xhr.status == 200){
//获取服务器的响应数据
var ret = xhr.responseXML;
var ele = ret.getElementsByTagName("return")[0];
alert(ele.textContent);
}
}
}
</script>
</head>
<body>
<input type="button" value="使用ajax方式调用webservice服务" onclick="sendAjax();">
</body>
</html>
requestBody 请求体,可以通过myeclipse自带插件,点击go以后,下边的请求体就是我们想要的格式。

二,使用urlconnection方式
package cn.demo.client.urlconnection;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection; /**
* 使用urlconnection方式调用webservice服务
* @author zhaoqx
*
*/
public class App {
public static void main(String[] args) throws Exception {
URL wsUrl = new URL("http://192.168.13.66:8080/hello");
HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection(); //构造请求体
String requestBody = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:q0=\"http://service.demo.cn/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "+
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"+
"<soapenv:Body><q0:sayHi><arg0>xiaoming</arg0></q0:sayHi></soapenv:Body></soapenv:Envelope>";
//设置请求的参数
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("content-type", "text/xml;charset=UTF-8"); //向服务端写数据
conn.getOutputStream().write(requestBody.getBytes()); int responseCode = conn.getResponseCode();
if(responseCode == 200){
//使用输入流获取服务端响应数据
InputStream in = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
StringBuffer sb = new StringBuffer();
while((len = in.read(b)) != -1){
String s = new String(b, 0, len,"UTF-8");
sb.append(s);
}
System.out.println(sb.toString());
in.close();
} }
}
上一篇:Use auto keyword in C++11


下一篇:PCB差分线学习