如何解析调用远程接口返回的xml数据 .
dom4j-1.6.1.jarjaxen-1.1-beta-6.jarjdom.jar此三jar包用于解析调用远程接口返回的xml数据,很方便,例如:package com.my.test;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;/** * 如何调用接口 * @author * */public class AnalysisXml {
public static void main(String args[]) throws DocumentException
{ String appserverIp = "10.137.121.51"; String appserverPort="8060"; String rqestXml ="<message><head><guid>mobile</guid></head><body><params><pwd>ads324sdsa4sf3w</pwd><callbacku
rl
/></params></body></message>";
//访问远程接口 String url = "http://" + appserverIp + ":" + appserverPort + "/eSpace/appserver/applogin.action"; String result = getHttp(rqestXml, url); //返回xml数据并解析 Document doc = DocumentHelper.parseText(result); String appid = doc.selectSingleNode("/message/body/params/appid").getText(); String tag = doc.selectSingleNode("/message/body/params/tag").getText(); String eid = doc.selectSingleNode("/message/body/params/eid").getText(); System.out.println(doc); } /** * 发送http请求 并得到响应数据流 * @param str * @param url * @return data String */ public static String getHttp(String str, String url) {try
{ URL server = new URL(url); HttpURLConnection httpConnection = (HttpURLConnection)server.openConnection(); httpConnection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); httpConnection.setRequestProperty("Accept", "application/x-www-form-urlencoded");
httpConnection.setRequestProperty("version", "100"); httpConnection.setConnectTimeout(120000); httpConnection.setReadTimeout(120000); httpConnection.setDoInput(true); httpConnection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(new BufferedOutputStream(httpConnection.getOutputStream()), "UTF-8");
out.write(str); out.flush(); out.close(); byte[] msgBody = null; DataInputStream dis = new DataInputStream(httpConnection.getInputStream()); int length = httpConnection.getContentLength(); //正常设置了Content-Length的值 if (length >= 0) { msgBody = new byte[length]; dis.readFully(msgBody); } // 未设置值 else { byte[] temp = new byte[1024]; int n = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((n = dis.read(temp)) != -1) { bos.write(temp, 0, n); } msgBody = bos.toByteArray(); bos.close(); } dis.close(); String data = new String(msgBody, "UTF-8").trim(); httpConnection.disconnect(); return data; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }}