首页 > 其他分享 >HttpURLConnection 调用soap 并且使用Dom4j解析多层级XML为Map对象

HttpURLConnection 调用soap 并且使用Dom4j解析多层级XML为Map对象

时间:2024-05-22 14:43:18浏览次数:28  
标签:XML Map String map Dom4j connection import HashMap log

1.引入dom4j的maven依赖包

<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.4</version>
</dependency>

2.转map方法

  1 import java.io.BufferedReader;
  2 import java.io.InputStreamReader;
  3 import java.io.OutputStream;
  4 import java.net.HttpURLConnection;
  5 import java.net.URL;
  6 import java.util.ArrayList;
  7 import java.util.HashMap;
  8 import java.util.List;
  9 
 10 import org.apache.log4j.Logger;
 11 import org.dom4j.Document;
 12 import org.dom4j.DocumentHelper;
 13 import org.dom4j.Element;
 14 import org.json.simple.JSONObject;
 15 
 16 public class TestDemoSoapService {
 17 public String getRequestXml() {
 18   return "" ;
 19 }
 20 public void handle()  {
 21         if (_log.isDebugEnabled()) {
 22             _log.debug("start handle");
 23         }
 24         String requestXmlString=getRequestXml();
 25         
 26         String strUrl = PropertiesConfiguration.getInstance().getString(
 27                 "soa.CorBnkAPI.url");
 28         // post serviceAPI
 29         HashMap<String, Object> httpPostMap = httpPost(requestXmlString, strUrl);
 30         
 31         if ("SUCCESS".equals(httpPostMap.get("sign"))) {
 32             _log.info(httpPostMap.get("data"));
 33             analysisXml(httpPostMap.get("data").toString());
 34         }
 35         
 36         
 37     }
 38 
 39 public HashMap<String, Object> httpPost(String param, String strUrl) {
 40         _log.info("PostServiceApi requestJson- EBS-MEPSIBFundTransfer-IU:"
 41                 + param);
 42         _log.info("PostServiceApi requeststrUrl- EBS-MEPSIBFundTransfer-IU:"
 43                 + strUrl);
 44         
 45         HttpURLConnection connection = null;
 46         BufferedReader reader = null;
 47         // sign
 48         String sign = "";
 49         String msgErro = "";
 50         String data = "";
 51         HashMap<String, Object> map = new HashMap<String, Object>();
 52         try {
 53             URL url = new URL(strUrl);
 54             connection = (HttpURLConnection) url.openConnection();
 55             connection.setRequestMethod("POST");
 56             // get over time(unit:s)
 57             String overTimeString = PropertiesConfiguration.getInstance()
 58                     .getString("soa.CorBnkAPI.OVERTIME");
 59             int overTime = Integer.valueOf(overTimeString) * 1000;
 60             connection.setConnectTimeout(overTime);
 61             connection.setDoOutput(true);
 62             connection.setDoInput(true);
 63             // soa.CorBnkAPI.XSourceId
 64             String XSourceId = PropertiesConfiguration.getInstance().getString(
 65                     "soa.CorBnkAPI.XSourceId");
 66             connection.setRequestProperty("XSourceId", XSourceId);
 67             String ApiKey = PropertiesConfiguration.getInstance().getString(
 68                     "soa.CorBnkAPI.Apikey");
 69             connection.setRequestProperty("ApiKey", ApiKey);
 70             
 71             connection.setRequestProperty("Content-Type","text/xml; charset=utf-8");
 72             connection.setRequestProperty("SOAPAction", "");
 73             connection.connect();
 74             OutputStream writer = connection.getOutputStream();
 75             String jsonInputString = param;
 76 
 77             byte[] input = jsonInputString.getBytes("utf-8");
 78             writer.write(input, 0, input.length);
 79 
 80             writer.flush();
 81             writer.close();
 82             int code = connection.getResponseCode();
 83             map.put("code", code);
 84             if (code == HttpURLConnection.HTTP_OK) {
 85                 try {
 86                     sign = "SUCCESS";
 87                     reader = new BufferedReader(new InputStreamReader(
 88                             connection.getInputStream(), "utf-8"));
 89                     String line;
 90                     while ((line = reader.readLine()) != null) {
 91                         data += line;
 92                     }
 93                     reader.close();
 94                 } catch (Exception e) {
 95                     _log.error("post-getInputStream:" + e.getMessage());
 96                     map.put("code", -1);
 97                     sign = "fAULT";
 98                     msgErro += e.getMessage();
 99                 }
100             } else {
101                 try {
102                     sign = "fAULT";
103                     reader = new BufferedReader(new InputStreamReader(
104                             connection.getErrorStream(), "utf-8"));
105                     String line;
106                     while ((line = reader.readLine()) != null) {
107                         msgErro += line;
108                     }
109                 } catch (Exception e) {
110                     _log.error("post-getErrorStream:" + e.getMessage());
111                     map.put("code", -1);
112                     sign = "fAULT";
113                     msgErro += e.getMessage();
114                 }
115             }
116             if (_log.isDebugEnabled()) {
117                 _log.debug("PostResult:" + data);
118             }
119         } catch (Exception e) {
120             _log.error("post-erro:" + e.getMessage());
121             map.put("code", -1);
122             sign = "fAULT";
123             msgErro += " E:" + e.getMessage();
124         } finally {
125             try {
126                 if (connection != null)
127                     connection.disconnect();
128             } catch (Exception e) {
129                 // TODO Auto-generated catch block
130                 map.put("code", -1);
131                 sign = "fAULT";
132                 msgErro += " E:" + e.getMessage();
133                 _log.error("post-erro(connection.disconnect):" + e.getMessage());
134             }
135         }
136         map.put("sign", sign);
137         map.put("msg", msgErro);
138         map.put("data", data);
139         _log.info("post-return:" + map.toString());
140         return map;
141     }
142 
143 
144 
145     public void analysisXml(String xmlString){
146         _log.info("start analysisXml:");
147         try {
148             //使用dom4j解析String Xml
149             Document document = DocumentHelper.parseText(xmlString);
150             Element root = document.getRootElement();
151             HashMap<String, Object>  map=new  HashMap<String, Object>();
152             map=parseElement(root);
153             _log.info(new  JSONObject(map));
154             _log.info(map.get("ServiceHeader").toString());
155         } catch (Exception e) {
156             // TODO: handle exception,map
157             _log.error("analysisXml fAULT:"+e.getMessage());
158         }
159         
160     }
161     //转map
162      private static HashMap<String, Object> parseElement(Element element) {
163          HashMap<String, Object> result = new HashMap<>();
164             List<Element> children = element.elements();
165             if (children.isEmpty()) {
166                 result.put(element.getName(), element.getText());
167             } else {
168                 for (Object child : children) {
169                     Element childElement = (Element) child;
170                     if (childElement.elements().isEmpty()) {
171                         result.put(childElement.getName(), childElement.getText());
172                     } else {
173                         HashMap<String, Object> childResult = parseElement(childElement);
174                         if (result.containsKey(childElement.getName())) {
175                             Object existingObject = result.get(childElement.getName());
176                             List<Object> list;
177                             if (existingObject instanceof List) {
178                                 list = (List<Object>) existingObject;
179                             } else {
180                                 list = new ArrayList<>();
181                                 list.add(existingObject);
182                             }
183                             list.add(childResult);
184                             result.put(childElement.getName(), list);
185                         } else {
186                             result.put(childElement.getName(), childResult);
187                         }
188                     }
189                 }
190             }
191             return result;
192         }
193      //根据key获取map的值
194      public static Object getValue(HashMap<?, ?> map, Object key) {
195             if (map.containsKey(key)) {
196                 return map.get(key);
197             } else {
198                 for (Object value : map.values()) {
199                     if (value instanceof HashMap) {
200                         Object result = getValue((HashMap<?, ?>) value, key);
201                         if (result != null) {
202                             return result;
203                         }
204                     }
205                 }
206             }
207             return null;
208         }
209 
210 
211 }

 

标签:XML,Map,String,map,Dom4j,connection,import,HashMap,log
From: https://www.cnblogs.com/paimianbaobao/p/18206193

相关文章

  • 关于vue-baidu-map的一些记录
    这一阶段主要的内容是负责编写和百度地图相关的信息。(写到我想吐)仿照导航的页面效果。1.使用说明这里使用的是vue-baidu-map相关组件,这里我就不去说明如何去安装他们了,我们直接向下看。vue-baidu-map的操作手册的网址:VueBaiduMap(dafrok.github.io)。当然我这里介绍的那些只......
  • kimi- MarkMap 生成思维导图
    1、Prompt:帮我分析《被人讨厌的勇气》这本书,从里面总结出核心内容,要求:1.提供5个主要观点2.每个观点至少有3个支撑观点说明3.按照以下格式,使用markdown的代码快格式输出:```#被人讨厌的勇气##<观点1>-<支撑观点1>-<支撑观点2>-<支撑观点3>##<观点2>-<支撑......
  • springboot集成logback-spring.xml日志文件
    logback-spring.xml:<!--Logbackconfiguration.Seehttp://logback.qos.ch/manual/index.html--><configurationscan="true"scanPeriod="10seconds"><springPropertyscope="context"name="logLevel"s......
  • jackson解析xml坑点
    为了获取xml数据,在springmvc中针对@ResponseBody配置了jackson。刚用的时候内心是狂喜的,终于不用自己解析了………… but…………………………还是有坑的……坑一:大小写问题@JacksonXmlProperty(localName="Apid")privateIntegerApid;privateIntegergetApid(){ ......
  • 错误: 找不到或无法加载主类 XXX类 || jmap -histo:live 2345 | less
    今天在学习jvm的时候,想要通过jmap-histo:live20368|less命令查看堆中存活对象信息。但是在windows系统中貌似好像不支持这个命令 于是我将自己的程序上传到了Linux系统中,但是经过编译完了之后,运行该class文件的时候,提示:错误:找不到或无法加载主类XXX类。这个错误的原......
  • 【FAQ】HarmonyOS SDK 闭源开放能力 —Map Kit(2)
    1.问题描述:能否设置点击地图,地图标记上的文字不消失?解决方案:你好,这个功能设计本身就是点击屏幕marker的信息窗消失;如果用户只是想信息窗中的文字一直展示,可以不用信息窗实现,建议可以使用自定义标记,通过在MarkerOptions中将icon属性设置为自定义图标的资源,可将默认标记图标修改......
  • Android查看apk安装包的AndroidManifest.xml文件
    Tips:当你看到这个提示的时候,说明当前的文章是由原emlog博客系统搬迁至此的,文章发布时间已过于久远,编排和内容不一定完整,还请谅解`Android查看apk安装包的AndroidManifest.xml文件日期:2020-4-19阿珏折腾代码浏览:946次评论:5条起因上周在做安卓系统的厂家推送功......
  • what's the advantages of using Map over Object in JavaScript?
    what'stheadvantagesofusingMapoverObjectinJavaScript?在JavaScript中使用Map相对于Object有什么优势?prosconsdemoshttps://leetcode.com/studyplan/30-days-of-javascript/(......
  • Spring是如何整合MyBatis将Mapper接口注册为Bean的原理
    一、接口生成bean定义1.首先MyBatis的Mapper接口核心是JDK动态代理2.Spring会排除接口,无法注册到IOC容器中3.MyBatis实现了BeanDefinitionRegistryPostProcessor可以动态注册BeanDefinition4.需要自定义扫描器(继承Spring内部扫描器ClassPathBeanDefinitionScan......
  • 【C#】【WriteableBitmap】保存图像到本地
    ///<summary>///保存图像到本地///</summary>///<paramname="wtbBmp"></param>///<paramname="name"></param>///<paramname="strDir"></param>///<returns></returns>......