//json页面返回格式{"data":{"blogs":[{"albid":865218,"id":12323,.....
org.json.JSONObject
//返回多个json里面的id值
public static List findimgCrawIdList(String url) {
List imgCrawIdList=new ArrayList();
try {
JSONObject jo = getJsonObj(url,"utf-8");
JSONObject menu = jo.getJSONObject("data");
JSONArray jsonArray = menu.getJSONArray("blogs");
for (int i = 0; i < jsonArray.length(); i++) {
imgCrawIdList.add(jsonArray.getJSONObject(i).get("id"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imgCrawIdList;
}
/**
* 根据网址,返回JSONObject对象
* 注:只适合请求响应为json格式网址
* @param src 来源网址
* @param code 编码方式
* @author chitianxiang $22th March, 2012 - 2:42 p.m
*/
private static JSONObject getJsonObj(String src, String code) {
InputStreamReader reader = null;
BufferedReader in = null;
try {
URL url = new URL(src);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(1000);
reader = new InputStreamReader(connection.getInputStream(), code);
in = new BufferedReader(reader);
String line = null; //每行内容
int lineFlag = 0; //标记: 判断有没有数据
StringBuffer content = new StringBuffer();
while ((line = in.readLine()) != null) {
content.append(line);
lineFlag++;
}
return lineFlag == 0 ? null : new org.json.JSONObject(content.toString());
} catch (SocketTimeoutException e) {
System.out.println("连接超时!!!");
return null;
} catch (JSONException e) {
System.out.println("网站响应不是json格式,无法转化成JSONObject!!!");
return null;
} catch (Exception e) {
System.out.println("连接网址不对或读取流出现异常!!!");
return null;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
System.out.println("关闭流出现异常!!!");
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println("关闭流出现异常!!!");
}
}
}
}