针对多个XML请求 .
json序列化包:com.alibaba.fastjso
- 发起请求方法
public JSONObject XMLRequest(String methodName, String url, String paramsss) throws JsonProcessingException {
RestTemplate restTemplate = new RestTemplate();
String xmlInfo = getXmlInfo(methodName, paramsss);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_XML);
HttpEntity entity = new HttpEntity(xmlInfo, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
String body = response.getBody();
String s = subString(body, "<" + methodName + "Result>", "</" + methodName + "Result>");
return JSON.parseObject(s);
}
return null;
}
- 拼接XML请求体
private String getXmlInfo(String methodName, String params) {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version='1.0' encoding='UTF-8'?>");
sb.append("<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' >");
sb.append("<soap:Body>");
sb.append(" <" + methodName + " xmlns='http://www.data86.net/'>");
sb.append("" + params + "");
sb.append(" </" + methodName + ">");
sb.append(" </soap:Body>");
sb.append(" </soap:Envelope>");
return sb.toString();
}
- 截取返回体中的内容
public String subString(String str, String strStart, String strEnd) {
/* 找出指定的2个字符在 该字符串里面的 位置 */
int strStartIndex = str.indexOf(strStart);
int strEndIndex = str.indexOf(strEnd);
/* index 为负数 即表示该字符串中 没有该字符 */
if (strStartIndex < 0) {
return "字符串 :---->" + str + "<---- 中不存在 " + strStart + ", 无法截取目标字符串";
}
if (strEndIndex < 0) {
return "字符串 :---->" + str + "<---- 中不存在 " + strEnd + ", 无法截取目标字符串";
}
/* 开始截取 */
String result = str.substring(strStartIndex, strEndIndex).substring(strStart.length());
return result;
}
eg:`
public String LYHLogin() throws JsonProcessingException {
String url = "http://121.89.178.60/WebServices/UserAdminService.asmx";
String paramsss = "<LoginName>*****</LoginName> <LoginPwd>*****</LoginPwd>";
JSONObject login = XMLRequest("Login", url, paramsss);
return login.get("Guid").toString();
}