//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()); Listlist = 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>