欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

Java+自定义XML请求

时间:2023-06-09

针对多个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 response = restTemplate.postForEntity(url, entity, String.class); if (response.getStatusCode().is2xxSuccessful()) { String body = response.getBody(); String s = subString(body, "<" + 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(""); sb.append(""); sb.append(" <" + methodName + " xmlns='http://www.data86.net/'>"); sb.append("" + params + ""); sb.append(" "); sb.append(" "); sb.append(" "); return sb.toString(); }

截取返回体中的内容

public String subString(String str, String strStart, String strEnd) { int strStartIndex = str.indexOf(strStart); int strEndIndex = str.indexOf(strEnd); 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 = "***** *****"; JSONObject login = XMLRequest("Login", url, paramsss); return login.get("Guid").toString(); }

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。