集册 Java实例教程 从url读取json字符串并创建json对象

从url读取json字符串并创建json对象

欢马劈雪     最近更新时间:2020-01-02 10:19:05

444
从url读取json字符串并创建Json对象
//来 自 n o w j a v a . c o m - 时代Java

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.Reader;

import java.net.URL;

import java.nio.charset.Charset;


import org.json.JSONException;


import org.json.JSONObject;


public class JsonReader {


    private static String readAll(Reader rd) throws IOException {
    /*
     from 时代Java - nowjava.com 
    */

        StringBuilder sb = new StringBuilder();

        int cp;

        while ((cp = rd.read()) != -1) {

            sb.append((char) cp);

        }

        return sb.toString();

    }


    public static JSONObject readJsonFromUrl(String url)

            throws IOException, JSONException {

        InputStream is = new URL(url).openStream();

        try {

            BufferedReader rd = new BufferedReader(new InputStreamReader(

                    is, Charset.forName("UTF-8")));

            String jsonText = readAll(rd);

            JSONObject json = new JSONObject(jsonText);

            return json;

        } finally {

            is.close();

        }

    }


    public 
展开阅读全文