<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());
}
}
APIStore使用例子(获取易源笑话)
最新推荐文章于 2024-07-17 19:48:32 发布