webservice介面三連擊之third
上篇部落格webservice介面三連擊之second我們講解了如何用soap ui 工具解析webservice介面,今天我們將介紹用java實現webservice介面的呼叫。
1.首先寫了一個http的工具類,用來發送符合http協議的請求,程式碼如下:
package com.noblelift.imp.platform.core.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.io.InputStream;
import org.json.XML;
import net.sf.json.JSONObject;
/**
* 後端呼叫第三方webservice介面
* @author zds 2018-12-27 16:33:50
*
*/
public class WebServiceUtil {
/**
*
* @param url 第三方系統提供webservice的介面url
* @param method 第三方系統提供webservice對應的方法名
* @param soapXML 第三方系統提供webservice對應的方法請求引數
* @return 第三方系統返回的JSONObject呼叫結果
* @throws Exception 工具類一般不處理具體異常,丟擲由呼叫方處理,否則容易形成黑箱
*/
public static JSONObject process(String url,String method, String soapXML) throws Exception{
//構建返回值
JSONObject result = new JSONObject();
//第一步:建立服務地址
URL netUrl = new URL(url);
//第二步:開啟一個通向服務地址的連線
HttpURLConnection connection = (HttpURLConnection) netUrl.openConnection();
//第三步:設定引數
connection.setRequestMethod("POST");
//設定超時時間
connection.setConnectTimeout(50000);
//3.2設定資料格式:content-type
connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
//3.3設定輸入輸出,因為預設新建立的connection沒有讀寫許可權,
connection.setDoInput(true);
connection.setDoOutput(true);
//將資訊以流的方式傳送出去
OutputStream os = connection.getOutputStream();
os.write(soapXML.getBytes());
//第五步:接收服務端響應,列印
int responseCode = connection.getResponseCode();
if(200 == responseCode){//表示服務端響應成功
//獲取當前連線請求返回的資料流
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String temp = null;
while(null != (temp = br.readLine())){
sb.append(temp);
}
//列印結果
String ret=sb.toString();
if(ret.startsWith("<?"))
ret = ret.replaceAll("\\<\\?.+\\?\\>", "<?xml version='1.0' encoding='UTF-8'?>");
else
ret = (new StringBuilder("<?xml version='1.0' encoding='UTF-8'?>")).append(ret).toString();
String now = xml2jsonString(ret);
System.out.println("列印返回結果轉成jsonString-------------"+now);
result =JSONObject.fromObject(now);
is.close();
isr.close();
br.close();
//關閉連線
connection.disconnect();
}
os.close();
return result;
}
/**
* string轉化成JSON
* @param xml檔案的string格式
* @return
* @throws Exception工具類一般不處理具體異常,丟擲由呼叫方處理,否則容易形成黑箱
*/
public static String xml2jsonString(String xml) throws Exception {
org.json.JSONObject xmlJSONObj = XML.toJSONObject(xml);
return xmlJSONObj.toString();
}
/**
* 獲得要傳送的webservice的xml形式的引數
* @param form查詢條件
* @return
*/
private static String getXML(HashMap<String,String> form,String method){
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?> ");
sb.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webserviceTest/\">");
sb.append("<soapenv:Header/>");
sb.append("<soapenv:Body>");
sb.append("<web:"+method+">");
// 設定請求引數
for(Iterator<String> it = form.keySet().iterator();it.hasNext();){
String key = it.next();
String value = form.get(key);
sb.append(" <"+key+">"+value+"</"+key+">");
}
sb.append("</web:"+method+">");
sb.append("</soapenv:Body>");
sb.append("</soapenv:Envelope>");
System.out.println("getXML傳送資料-----------------"+sb.toString());
return sb.toString();
}
public static void main(String[] args) throws Exception {
String url = "http://192.168.81.137:8080/Service/ServiceHello";
String method="loginTest";
HashMap<String,String> form = new HashMap<String,String>();
form.put("name", "admin");
form.put("password", "123456");
//組織SOAP資料,傳送請求
String soapXML = getXML(form,method);
//非必填欄位
JSONObject ret = WebServiceUtil.process(url,method,soapXML);
JSONObject Envelope = ret.optJSONObject("S:Envelope");
JSONObject Body = Envelope.optJSONObject("S:Body");
JSONObject loginTestResponse = Body.optJSONObject("ns2:loginTestResponse");
String Out = loginTestResponse.optString("return");
System.out.println("例子:查詢結果-----------------"+Out);
}
}
2.這裡從mian方法開始介紹,第一行http請求的url,可以在soap UI工具頁面看到,如下圖:
上圖的1處就是http請求url的路徑,已經解析出來,main方法第二行method的值就是介面對應的方法名為loginTest,form就是需要傳的引數的集合,組織好form後呼叫工具方法getXML(form,method)即可得到http請求的xml形式的引數, getXML工具方法的內容其實就是上圖 2處的xml內容,到這裡引數都組織完畢,直接呼叫寫好的http工具方法WebServiceUtil.process(url,method,soapXML)即可,然後就會接收到服務端返回的資訊,該返回值是個Json,就是上圖3處的xml格式的資料,其中我們只需要取到return欄位,具體的操作如main方法所示,到這裡呼叫介面就完成了,值得注意的是getXML中組織的引數資訊對於不同的介面需要特殊處理,可直接複製soap UI解析的xml引數資訊(Soap UI是個強大的工具)。
4.main方法執行結果如下:
getXML傳送資料-----------------<?xml version="1.0" encoding="utf-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webserviceTest/"><soapenv:Header/><soapenv:Body><web:loginTest> <password>123456</password> <name>admin</name></web:loginTest></soapenv:Body></soapenv:Envelope>
列印返回結果轉成jsonString-------------{"S:Envelope":{"xmlns:S":"http://schemas.xmlsoap.org/soap/envelope/","S:Body":{"ns2:loginTestResponse":{"xmlns:ns2":"http://webserviceTest/","return":"賬號(null)不存在,請查證後重新輸入!"}}}}
例子:查詢結果-----------------賬號(null)不存在,請查證後重新輸入!