问题
在请求接口时,接口响应结果乱码,通过平常的编码格式转化来解码不能解决,观察接口的响应内容编码为Content-encoding: gzip
。
解决办法
public static String uncompressString(String str) {
if (StringUtil.isEmpty(str)) {
return str;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes(StandardCharsets.ISO_8859_1));
GZIPInputStream gzipStream;
try {
gzipStream = new GZIPInputStream(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
byte[] buffer = new byte[256];
int n;
while (true) {
try {
if (!((n = gzipStream.read(buffer)) >= 0)) break;
} catch (IOException e) {
throw new RuntimeException(e);
}
outputStream.write(buffer, 0, n);
}
return outputStream.toString();
}
参考博客
请求网站响应的文本带有乱码,原来是Content-encoding惹的祸,一文带你搞懂Content-encoding、Accept-Encoding