从URL获取JSON字符串转成JSONObject

private static JSONObject getObjectFromUrl(String s) throws IOException{
		StringBuffer buffer = new StringBuffer();
		// 通过js的执行路径获取后台数据进行解析
		URL url = new URL(s);
		HttpURLConnection http = (HttpURLConnection) url.openConnection();
		http.setDoOutput(true);
		http.setDoInput(true);
		http.setUseCaches(false);
		http.setRequestMethod("GET");
		http.connect();
		// 将返回的输入流转换成字符串
        InputStream inputStream = http.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        bufferedReader.close();
        inputStreamReader.close();
        // 释放资源
        inputStream.close();
        inputStream = null;
        http.disconnect();
        str = buffer.toString();
		int index = str.indexOf("(");
        String jsonString = str.substring(index + 1, str.length() -1);
		JSONObject jo = JSONObject.fromObject(jsonString);
		return jo;
	}
	public static void main(String[] args) throws IOException {
		JSONObject jo=getObjectFromUrl("URL");
		//当前页文章数组
		JSONArray jsonArray = JSONArray.fromObject(jo.get("list")); 
			int arrlength=jsonArray.size();
			for(int j=0;j

你可能感兴趣的:(java)