首先,加入依赖包:
<!-- POJO->XML/JSON,XML/JSON->POJO --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.6.0</version> </dependency>
假设一个HTTP请求的返回为XML格式:
<returnsms> <returnstatus>Success</returnstatus> <message>ok</message> <remainpoint>11032</remainpoint> <taskID>4354699</taskID> <successCounts>1</successCounts> </returnsms>
简单地把这些XML转换为MAP对象的方法:
URL url = new URL("http://www.abc.com/yyy"); // 打开url连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置url请求方式 ‘get’ 或者 ‘post’ connection.setRequestMethod("POST"); // 发送 InputStream is = url.openStream(); // 转换返回值 @SuppressWarnings("unchecked") Map<String,String> m = new XmlMapper().readValue(is,Map.class); String returnstatus = m.get("returnstatus"); if ("Success".equals(returnstatus)) {// 返回成功 logger.info("成功!"); } else { logger.error("失败! cause:{}",m.get("message")); }