2

我的代码中有以下两种方法。现在,我可以根据以下代码从 URL 读取 JSON。但是,我应该如何修改代码以便获得 gzip 文件,然后将其解码为 JSON?

private static String readAll(Reader rd) throws IOException {
    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);
      Log.e("size of text", jsonText.length()+"");

      JSONObject json;
      if (jsonText.contains("</div>")) {
          json = new JSONObject(jsonText.split("</div>")[1]);
      } else {
          json = new JSONObject(jsonText);
      }
      return json;
    } finally {
      is.close();
    }
}
4

2 回答 2

3
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {

    HttpUriRequest request = new HttpGet(url);
    request.addHeader("Accept-Encoding", "gzip");
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);

    InputStream instream = response.getEntity().getContent();
    org.apache.http.Header contentEncoding = response.getFirstHeader("Content-Encoding");

    JSONObject json = null;
    if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
        BufferedReader rd = new BufferedReader(new InputStreamReader(new GZIPInputStream(instream)));
        String jsonText = readAll(rd);
          if (jsonText.contains("</div>")) {
              json = new JSONObject(jsonText.split("</div>")[1]);
          } else {
              json = new JSONObject(jsonText);
          }
    }
    return json;
}
于 2013-02-04T11:07:00.437 回答
2

该代码可以使用 aGZIPInputStream来读取 GZipped JSON 数据。

public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {

    InputStream is = new URL(url).openStream();
    try {
      //GZIP InputStream
      BufferedReader rd = new BufferedReader(new InputStreamReader(new GZIPInputStream(is), Charset.forName("UTF-8")));
      //Rest of code...
    } finally {
      is.close();
    }
}

文档

为了更有效地迭代,InputStream您可以一次读取整行。

private static String readAll(BufferedReader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    String inputLine;

    while ((inputLine = rd.readLine()) != null){
       sb.append(inputLine);
    }

    return sb.toString();
}

完整示例(已测试)

public class StackExample {

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            readJsonFromUrl("https://api.stackexchange.com/2.1/answers?order=desc&sort=activity&site=stackoverflow");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private static String readAll(BufferedReader rd) throws IOException {
           StringBuilder sb = new StringBuilder();
            String inputLine;

            while ((inputLine = rd.readLine()) != null){
               sb.append(inputLine);
            }

            return sb.toString();
    }

    public static void readJsonFromUrl(String url) throws IOException{

        InputStream is = new URL(url).openStream();
        try {
          BufferedReader rd = new BufferedReader(new InputStreamReader(new GZIPInputStream(is), Charset.forName("UTF-8")));
          String jsonText = readAll(rd);
          System.out.println(jsonText);
        } finally {
          is.close();
        }
    }

}
于 2013-02-04T10:17:03.550 回答