好记忆,不如烂笔头...
简介
SOAP :简单对象访问协议,在几年前的时间里,横行互联网中的各个系统,不过事过境迁了。。。
但是对于已经架构好的 SOAP 协议的系统,新的系统照样需要和原来系统进行系统交互的时候,照样的遵照SOAP协议来通信,获取数据。
实现
1.准备工作
httpclient-4.3.6.jar ;httpcore-4.3.2.jar ; httpmime-4.3.6.jar 三个需要访问的jar
2. 请求头代码
/**
* soap 请求.
*
* @param requestBody
* @param requestUrl
* @return
*/
public static final CloseableHttpClient client = HttpClients.createDefault();
private static String SendPostRequest(String requestBody,String requestUrl) {
HttpPost post = new HttpPost(requestUrl);
try {
post.setEntity(new StringEntity(requestBody));
} catch (UnsupportedEncodingException ignored) {
}
CloseableHttpResponse response = null;
String result = null;
try {
response = client.execute(post);
String data = IOUtils.toString(response.getEntity().getContent());
int begin = data.indexOf("{");
int end = data.lastIndexOf("}");
result = data.substring(begin, end+1);
} catch (IOException ignored) {
ignored.printStackTrace();
} finally {
HttpClientUtils.closeQuietly(response);
}
return result;
}
3. 拼装soap协议的xml文件进行通信
附上一个检查系统email,phone,user_name 的xml 拼装代码
public static boolean CheckSouyueUserPropertyExists(String propKey, String propValue) {
StringBuilder sb=new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sb.append("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"http://usercenter.zhongsou.com/soap\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:ns2=\"http://xml.apache.org/xml-soap\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
sb.append("<SOAP-ENV:Header>");
sb.append("<ns1:Auth SOAP-ENV:actor=\"http://schemas.xmlsoap.org/soap/actor/next\">");
sb.append("<item>");
sb.append("<key>user_name</key>");
sb.append("<value>"+AUTH_USER_NAME+"</value>");
sb.append("</item>");
sb.append("<item>");
sb.append("<key>pwd</key>");
sb.append("<value>"+AUTH_PWD+"</value>");
sb.append("</item>");
sb.append("<item>");
sb.append("<key>sign</key>");
sb.append("<value>"+AUTH_SIGN+"</value>");
sb.append("</item>");
sb.append("</ns1:Auth>");
sb.append("</SOAP-ENV:Header>");
sb.append("<SOAP-ENV:Body>");
if (propKey.equalsIgnoreCase("email")) {
sb.append("<ns1:CheckEmailExists>");
sb.append("<value>"+propValue+"</value>");
sb.append("</ns1:CheckEmailExists>");
}else if (propKey.equalsIgnoreCase("phone")) {
sb.append("<ns1:CheckPhoneExists>");
sb.append("<value>"+propValue+"</value>");
sb.append("</ns1:CheckPhoneExists>");
}else {
sb.append("<ns1:CheckUserNameExists>");
sb.append("<value>"+propValue+"</value>");
sb.append("</ns1:CheckUserNameExists>");
}
sb.append("</SOAP-ENV:Body>");
sb.append("</SOAP-ENV:Envelope>");
String requestBody = sb.toString();
System.out.println(requestBody);
return requestBody;
}
剩下的就是开始调用SendPostRequest()方法来测试了。。。
其实没有什么好的实现方式,就只能是通过自己拼装xml来实现了
巨啃爹的事情。。。