简述:
解析xml
(参考:http://7-sun.com/text/23790.html)
maven dependency
<dependency>
<groupId>maven</groupId>
<artifactId>dom4j</artifactId>
<version>1.7-20060614</version>
</dependency>
代码:
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ShortUrlUtil {
private static Logger logger = LoggerFactory.getLogger(ShortUrlUtil.class);
public static int TIMEOUT = 30 * 1000;
public static String ENCODING = "UTF-8";
public static void main(String[] args) {
try{
URL url = new URL("http://api.189.cn/EMP/shorturl/long2short?");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//POST Request Define:
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setConnectTimeout(TIMEOUT);
connection.setRequestMethod("POST");
// POST params
StringBuilder sbd = new StringBuilder();
sbd.append("param=").append("param1");
connection.getOutputStream().write(sbd.toString().getBytes());
connection.connect();
// response string
String responseStr = getResponseStr(connection);
System.out.println("response xml : \n" + responseStr);
// process response
String res_message = getValueByKey_XML(responseStr, "res_message");
System.out.println("\nget res_message: \n" + res_message);;
}catch(IOException e){
e.printStackTrace();
}
}
/**
* XML 解析
* get value by key
* @param replyText
* @param key
* @return
*/
private static String getValueByKey_XML(String replyText, String key){
String result = "";
SAXReader reader = new SAXReader();
ByteArrayInputStream bais = new ByteArrayInputStream(replyText.getBytes());
Document doc = null;
try {
doc = reader.read(bais);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Element root = doc.getRootElement();
Iterator nodes = root.elementIterator();
while(nodes.hasNext()){
Element node = (Element) nodes.next();
if(key.equals(node.getName())){
result = node.getText();
}
}
return result;
}
/**
* 通过HttpConnection 获取返回的字符串
* @param connection
* @return
* @throws IOException
*/
private static String getResponseStr(HttpURLConnection connection)
throws IOException{
StringBuffer result = new StringBuffer();
int responseCode = connection.getResponseCode();
if (responseCode == connection.HTTP_OK) {
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, ENCODING));
String inputLine = "";
while ((inputLine = reader.readLine()) != null) {
result.append(inputLine);
}
}
return String.valueOf(result);
}
}
输出: