Web Service 客戶端的幾種方式
阿新 • • 發佈:2019-01-09
由於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>