我的代码中有以下两种方法。现在,我可以根据以下代码从 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();
}
}