Java调用百度寻人API小实例

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) {
				}
			}
		}

	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值