java 解析http返回xml數據


//post 請求
private static String sendPost(String url, String urlParameters) throws Exception { URL obj = new URL(url + urlParameters); System.out.print("URL:" + url + urlParameters); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); StringBuffer response = new StringBuffer(); int responseCode = con.getResponseCode(); if (responseCode == 200) { BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } else { logger.info("Http request error code :" + responseCode); } return response.toString(); }

  2.解析xml數據

private JSONObject parseXML(String Data, String returnType) {
JSONObject jsonObject = null;
if ("xml".equals(returnType)) {
org.dom4j.Document document = DocumentHelper.parseText(buffer.toString());
List<Element> list = document.getRootElement().elements();
jsonObject = new JSONObject();
for (int i = 0; i < list.size(); i++) {
jsonObject.put(list.get(i).getName(), list.get(i).getData());
}

} else {

jsonObject = JSONObject.parseObject(buffer.toString());
}
return jsonObject;

}

  xml數據示例

<?xml version="1.0" encoding="UTF-8"?>
<result>
<response>1</response>
<sms>
<phone>13738085232</phone>
<pno>EAE7958C84DE0013288F51C9FA7E683E</pno>
<state>10</state><
description>Reserved</description>
</sms>
</result>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM