Java之http请求乱码问题解决
这周由于项目需要请求一个接口,获取数据,反复尝试,请求的数据始终乱码。这里简单的总结一下解决乱码的几个方法。
首先,需要注意的是编码方式的一致,其次对方怎么编码,接收方怎么解码即可。
先看一下请求数据的一般写法:
public static void main(String [] args){ StringBuffer buffer = new StringBuffer(); //获取连接 URL url = new URL("XXXXXX"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(3 * 1000); //设置请求头 connection.setRequestProperty("Charset","UTF-8"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"); connection.setRequestProperty("Referer","XXXXXX"); connection.setRequestProperty("Accept","application/json,text/plain,*/*"); connection.setRequestProperty("Accept-Encoding", "gzip,deflate"); connection.connect();
//设置编码格式“utf-8”、“gbk”、“gb2312
” BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); connection.disconnect();
System.out.println(buffer); }
我们通过查询编码,为 UTF-8
,但是我设置请求编码为UTF-8
,照样乱码。有点怀疑是网站的故意设置了,后来让同事通过python请求数据是没有问题的,才意识到或许是我代码有问题。后来发现我忽略了,响应头。
最终在网上找到了解决办法。
用java.util.zip
下的工具类来解压输入流,详细代码如下:
//具体处理代码与上面一样,只需要对输入流进行解压即可
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new GZIPInputStream(
connection.getInputStream()),"utf-8");
stay hungry, stay foolish