请问,如果网站提供的json格式被压缩 (如gz档)
如网站 http://data.taipei/bus/ROUTE
使用okhttp要如何解压缩后取得json格式的资料?
未压缩的json资料以下面的程式码接收正常,如要接收压缩后的json资料要如何修改 ?
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
取得资料后,我在网络上查到解密的程式码(后面有叙述)。我先把json转成byte[]
byte[] bZipJson = json.getBytes("utf-8");
后呼叫此function :
String json1 = uncompressToString(bZipJson,"utf-8");
不过在 GZIPInputStream gunzip = new GZIPInputStream(in);
出现 java.io.IOException: unknown format (magic number ef1f) 错误
我确认过,此档案为gz档没错,是哪里出问题了 ?
网络程式码如下:
public static String uncompressToString(byte[] b, String encoding) {
if (b == null || b.length == 0) {
Print("bus=>b=null");
return null;
}
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(b);
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toString(encoding);
} catch (Exception e) {
Print("bus=>1Error:unzip : " + e.toString() );
e.printStackTrace();
return null;
}
//return "aaa";
}