APIStore使用例子(获取易源笑话)

<pre name="code" class="java">package Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class BaiduApiStore {
	
	/*
	 * 请求示例
	 */
	public static String request(String httpUrl, String httpArg) {

		BufferedReader br = null;
		String strRead = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		httpUrl = httpUrl + "?" + httpArg;
		try {
			URL url = new URL(httpUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setRequestProperty("apikey", "你自己的apikey");
			connection.connect();
			InputStream is = connection.getInputStream();
			br = new BufferedReader(new InputStreamReader(is, "utf-8"));
			while ((strRead = br.readLine()) != null) {
				sbf.append(strRead);
				sbf.append("\r\n");
			}
			br.close();
			result = sbf.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;

	}

	/*
	 * 解析易源_笑话大全
	 * (JSON格式主要为<span style="color:#ff0000;">键值对</span>{key:value}和<span style="color:#ff0000;">数组</span>[]的套用,慢慢解析出自己需要的内容就行)
	 * 定义一个实体类来暂时保存数据
	 */
	public static List<Joke> analysis(String jsonResult) {
		List<Joke> list = new ArrayList<Joke>();
		JSONObject ja = JSONObject.<span style="color:#cc0000;">fromObject(jsonResult)</span>;//初始化
		JSONObject jb = (JSONObject) ja.get("showapi_res_body");//key-value(JSONObject)
		JSONArray ac = jb.getJSONArray("contentlist");//key-value(JSONArray)
		for (int i = 0; i < ac.size(); i++) {
			JSONObject jd = (JSONObject) <span style="color:#ff0000;">ac.opt(i)</span>;//数组每一个元素又为一个JSONObject
			Joke joke = new Joke();
			joke.setTitle(jd.getString("title"));
			System.out.println(joke.getTitle());
			joke.setText(jd.getString("text"));
			System.out.println(joke.getText());
			list.add(joke);
		}
		return list;
	}
	/*
	 * 测试
	 */
	public static void main(String[] args) {
		String httpUrl = "http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text";
		String httpArg = "page=1";
		String jsonResult = BaiduApiStore.request(httpUrl, httpArg);
		System.out.println(jsonResult);
		List<Joke> list = BaiduApiStore.analysis(jsonResult);
		System.out.println(list.size());
	}
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值