gpt4 book ai didi

java - Android 压缩包

转载 作者:太空狗 更新时间:2023-10-29 16:43:04 25 4
gpt4 key购买 nike

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

最佳答案

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;
}

关于java - Android 压缩包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14684534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com