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

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格式主要为键值对{key:value}和数组[]的套用,慢慢解析出自己需要的内容就行)
	 * 定义一个实体类来暂时保存数据
	 */
	public static List analysis(String jsonResult) {
		List list = new ArrayList();
		JSONObject ja = JSONObject.fromObject(jsonResult);//初始化
		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) ac.opt(i);//数组每一个元素又为一个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 list = BaiduApiStore.analysis(jsonResult);
		System.out.println(list.size());
	}
}


 
 

你可能感兴趣的:(Java)