package net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class TestSearch {
/**
* @param args
* @throws SAXException
* @throws ParserConfigurationException
*/
public static void main(String[] args) throws ParserConfigurationException, SAXException {
StringBuffer sb = new StringBuffer();
// API地址
sb.append("http://opendata.baidu.com/api.php?resource_id=6109&from_mid=1");
// 以GET形式请求,构建请求参数
// 格式
sb.append("&format=xml");
// 编码
sb.append("&ie=utf-8&oe=utf-8");
// 搜索参数
sb.append("&query=地震");
// 从第0条开始,获取10条
sb.append("&rn=10&pn=0");
// ------------------ 发起请求
InputStream in = null;
BufferedReader br = null;
try {
URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
// 连接成功
if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
in = conn.getInputStream();
// 创建一个匿名解析器,使用SAX解析
DefaultHandler handler = new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
super.startElement(uri, localName, qName, attributes);
if ("data".equals(qName)) {
System.out.println("\n");
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
super.characters(ch, start, length);
System.out.print(new String(ch, start, length) + "\t");
}
};
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(in, handler);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
}
}
if (br != null) {
try {
br.close();
} catch (Exception e) {
}
}
}
}
}