WebService的實現方式之一就是基於HTTP發送SOAP報文進行調用。
可能由於各種原因,我們不能使用CXF、AXIS等框架調用,此時的解決方案之一就是直接基於HTTP發送SOAP報文,然后將響應報文當作XML進行處理。
廢話不多,直接上代碼:
需要導入類:
1 import org.apache.commons.httpclient.HttpClient; 2 import org.apache.commons.httpclient.UsernamePasswordCredentials; 3 import org.apache.commons.httpclient.auth.AuthScope; 4 import org.apache.commons.httpclient.methods.PostMethod; 5 import org.apache.commons.httpclient.methods.RequestEntity; 6 import org.apache.commons.httpclient.methods.StringRequestEntity; 7 import org.apache.commons.httpclient.params.HttpClientParams;
核心代碼:
private String invokeService(String operationName, BaseRequestModel requestModel) throws Exception { String url = endpointUrl; String userName = "beiifeng"; String password = "beiifeng"; int timeOut = 60; String targetNameSpace = "http://service.ws.beiifeng.com"; // 創建Http客戶端 HttpClient httpclient = new HttpClient(); // 權限用戶驗證 httpclient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); PostMethod post = null; try { post = new PostMethod(url); HttpClientParams params = new HttpClientParams(); params.setSoTimeout(timeOut * 1000); httpclient.setParams(params); RequestEntity entity = new StringRequestEntity(this.formatSOAPRequest(operationName, targetNameSpace, requestModel), "text/xml", "UTF-8"); post.setRequestEntity(entity); int result = httpclient.executeMethod(post); //異常 String res = post.getResponseBodyAsString(); if (result != 200) { throw new RuntimeException("調用webservice失敗:服務器端返回HTTP code " + result + "\n信息:" + res); } return res; } catch (Exception e) { throw e; } finally { if (post != null) { post.releaseConnection(); } } } private String formatSOAPRequest(String operationName, String targetNameSpace, BaseRequestModel requestModel) { StringBuffer sb = new StringBuffer(); sb.append("<SOAP-ENV:Envelope xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" " + "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://" + "www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instanc" + "e\">\n"); sb.append("<SOAP-ENV:Body>\n"); sb.append("<m:" + operationName + " xmlns:m=\"" + targetNameSpace + "\">\n"); sb.append(requestModel.requestModelToString()); sb.append("</m:" + operationName + ">\n"); sb.append("</SOAP-ENV:Body>\n"); sb.append("</SOAP-ENV:Envelope>\n"); return sb.toString(); }
請求實體類繼承自BaseRequestModel,代碼如下:
public abstract class BaseRequestModel { /** * 將請求實體轉換為類似XML字符串 * * @return soapAction中的XML格式字符串 */ public abstract String requestModelToString(); }
總結:其中滋味,各位看客自行體會:p
<<endl