由于Web Service 的SOAP协议是基于HTTP协议之上,因此所有基于HTTP的方式都能调用Web Service.
1、使用URLConnection发送请求.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class WebserviceClientT {
/**
* 使用Connection 连接WebService
* @param _url
* @param _nameSpase
* @param _methodName
* @param _requestStr
*/
public void UrlConnection2WebService(String _url, String _nameSpase, String _methodName, String _requestStr){
//服务的地址
URL wsUrl = null;
OutputStream os = null;
InputStream is = null ;
HttpURLConnection conn = null;
try {
wsUrl = new URL(_url);
conn = (HttpURLConnection) wsUrl.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
os = conn.getOutputStream();
//请求体
String soap = "<?xml version = \"1.0\" ?>"
+ "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+ "xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
+ "xmlns:web=\""+_nameSpase+"\">"
+ "<soapenv:Header/>"
+ "<soapenv:Body>"
+ "<web:"+_methodName+" soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
+ "<in0 xsi:type=\"web:"+ _methodName +"\">"
+ _requestStr
+ "</in0>"
+ "</web:"+_methodName+">"
+ "</soapenv:Body>"
+ "</soapenv:Envelope>";
os.write(soap.getBytes());
is = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
String result = "";
while((len = is.read(b)) != -1){
String ss = new String(b,0,len,"UTF-8");
result += ss;
}
System.out.println("返回结果:"+result);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.disconnect();
}
}
}
二、使用HttpClient.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* http 请求方式,使用dom4j对返回结果的XML进行了解析
* @author long
*/
public class WebserviceClient {
/**
* WebService只采用HTTP POST方式传输数据
* @param _url 请求的url地址
* @param _nameSpase 命名空间
* @param _methodName 方法名称
* @param _requestStr 请求数据
*/
public static void Http2WebService(String _url, String _nameSpase, String _methodName, String _requestStr){
String orderSoapXml = "<?xml version = \"1.0\" ?>"
+ "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+ "xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
+ "xmlns:web=\""+_nameSpase+"\">"
+ "<soapenv:Header/>"
+ "<soapenv:Body>"
+ "<web:"+_methodName+" soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
+ "<in0 xsi:type=\"web:"+ _methodName +"\">"
+ _requestStr
+ "</in0>"
+ "</web:"+_methodName+">"
+ "</soapenv:Body>"
+ "</soapenv:Envelope>";
PostMethod postMethod = new PostMethod(_url);
HttpClient httpClient = new HttpClient();
try {
byte[] b =orderSoapXml.toString().getBytes("UTF-8");
//将请求读入inputstream
InputStream is = new ByteArrayInputStream(b, 0, b.length);
RequestEntity re = new InputStreamRequestEntity(is, b.length, "text/xml; charset=utf-8");
postMethod.setRequestEntity(re);
//获取状态码
int statusCode = httpClient.executeMethod(postMethod);
if(statusCode == 200) {
System.out.println("调用成功!");
String result = postMethod.getResponseBodyAsString();
// System.out.println("调用结果:"+ result);
Document document = DocumentHelper.parseText(result);
Element root = document.getRootElement();
String str = root.getStringValue();
System.out.println("返回结果:"+str);
} else {
System.out.println("调用失败!错误码:" + statusCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
}
}
}
三、使用Axis2的RPC方式.
import javax.xml.namespace.QName;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;
public class Axis2Connection {
/**
* @param _url 请求地址
* @param _request 请求数据
* @param _namespaceURI 命名空间
* @param _localPart 要调用的方法名
*/
public static void rpcToWebService(String _url, String _request, String _namespaceURI, String _localPart){
// 使用RPC方式调用WebService
RPCServiceClient serviceClient;
String response = "";
try {
serviceClient = new RPCServiceClient();
Options options = serviceClient.getOptions();
//指定调用WebService的URL
EndpointReference targetEPR = new EndpointReference(_url);
options.setTo(targetEPR);
//设置参数值
Object[] opAddEntryArgs = new Object[]{_request};
// 指定返回值的数据类型的Class对象
Class[] classes = new Class[]{String.class};
//设置WSDL文件的命名空间及要调用的方法
QName opAddEntry = new QName(_namespaceURI, _localPart);
// RPCServiceClient类的invokeBlocking方法调用了WebService中的方法。
//invokeBlocking方法有三个参数,
//其中第一个参数的类型是QName对象,表示要调用的方法名;
//第二个参数表示要调用的WebService方法的参数值,参数类型为Object[];
//第三个参数表示WebService方法的返回值类型的Class对象,参数类型为Class[]。
//当方法没有参数时,invokeBlocking方法的第二个参数值不能是null,而要使用new Object[]{}。
Object[] objects = serviceClient.invokeBlocking(opAddEntry,opAddEntryArgs, classes);
response = objects[0].toString();
} catch (AxisFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("返回结果:"+response);
}
}
四、JavaScrip 的Ajax 方法.(安全性无保障)
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8"/>
<title>通过ajax调用WebService服务</title>
<script>
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
function sendMsg(){
//请求内容
var requestStr = document.getElementById('requestStr').value;
//服务的地址
var wsUrl = 'http://127.0.0.1:8080/myservice/seyHello';
//命名空间
var nameSpase = "http://www.service.mywebservice.org";
//方法名称
var methodName = "hello";
//请求体
var soap = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="'+nameSpase+'" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
+ ' <soapenv:Body> <q0:'+methodName+'><arg0>'
+ requestStr
+'</arg0></q0:'+methodName+'> </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 = ret.text;
// alert(ret.text);
}
}
}
</script>
</head>
<body>
<input type="button" value="发送SOAP请求" onclick="sendMsg();">
<input type="text" id="requestStr">
<div id="showInfo">
</div>
</body>
</html>