从URL获取JSON字符串转成JSONObject

来源:互联网 发布:全自动点胶机程序编程 编辑:程序博客网 时间:2024/06/06 03:15
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<arrlength;j++){JSONObject a = jsonArray.getJSONObject(j); }}

原创粉丝点击