Java后台需要访问一个外部api拿一些数据,但是网上大部分的那些代码运行起来的结果都是乱码。
大概就这样的:
URLConnection conn = url.openConnection();
conn.connect();
InputStream in = conn.getInputStream();
InputStreamReader inn = new InputStreamReader(in,"utf-8");
BufferedReader bufferedReader = new BufferedReader(inn);
String line;
StringBuilder builder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null){
builder.append(line);
}
System.out.println(builder.toString());
找遍了各种地方都没解决,比如什么ide编码,控制台编码等,都调成一致的utf8,但是还是乱码。
最后在群友的帮助下,了解到可能是数据还没有解压缩,需要添加一个GZIPInputStream类
修改后如下
URLConnection conn = url.openConnection();
conn.connect();
InputStream in = conn.getInputStream();
//解压input流内容
GZIPInputStream gzip = new GZIPInputStream(in);
InputStreamReader inn = new InputStreamReader(gzip,"utf-8");
BufferedReader bufferedReader = new BufferedReader(inn);
String line;
StringBuilder builder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null){
builder.append(line);
}
System.out.println(builder.toString());
这样改了以后再获取的数据就没有乱码问题了。
(不过这之中了解到一个叫hutool的Java工具包,非常好用,https://hutool.cn,上面这一长串的代码可以直接简化为一行HttpUtil.get(String Url)就解决了)