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