Java使用GZIP壓縮導(dǎo)致HTTP請(qǐng)求返回亂碼問(wèn)題解決
原因
用Java調(diào)用雪球的API,結(jié)果返回的是亂碼,一番研究后發(fā)現(xiàn)是因?yàn)榉祷氐臄?shù)據(jù)使用了GZIP壓縮,需要先解壓才能得到正確數(shù)據(jù)。
思路
使用了GZIP壓縮的數(shù)據(jù)在響應(yīng)頭里會(huì)有一項(xiàng)名為content-encoding的參數(shù),值為gzip。
Java中可以使用.getHeaderField()讀取響應(yīng)頭的參數(shù)。
如果沒(méi)有這項(xiàng)參數(shù),會(huì)返回null。
解決方法
用.getHeaderField("content-encoding")讀取content-encoding參數(shù)的值。
如果值不為空,通過(guò)值判斷是否用了gzip壓縮。
使用了gzip就解壓,沒(méi)用就不處理。
代碼
關(guān)鍵部分
// 獲取響應(yīng)頭content-encoding數(shù)據(jù),如果是gzip就解壓(以后可能要改成部分對(duì)比.contains()而不是全部對(duì)比) String contentEncoding = conn.getHeaderField("content-encoding"); if((contentEncoding != null)&&(contentEncoding.equals("gzip"))){ is = new GZIPInputStream(conn.getInputStream()); }else{ is = conn.getInputStream(); }
完整代碼
部分地方需要按需修改
import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.zip.GZIPInputStream; public class HttpURLConnectionTools { public String doPost(String URL, String jsonStr) { OutputStreamWriter out = null; BufferedReader in = null; InputStream is = null; StringBuilder result = new StringBuilder(); HttpURLConnection conn = null; try { java.net.URL url = new URL(URL); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); // 發(fā)送POST請(qǐng)求必須設(shè)置為true conn.setDoOutput(true); conn.setDoInput(true); // 設(shè)置連接超時(shí)時(shí)間和讀取超時(shí)時(shí)間 conn.setConnectTimeout(30000); conn.setReadTimeout(10000); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); // 獲取輸出流 out = new OutputStreamWriter(conn.getOutputStream()); out.write(jsonStr); out.flush(); out.close(); // 取得輸入流,并使用Reader讀取 if (200 == conn.getResponseCode()) { // 獲取響應(yīng)頭content-encoding數(shù)據(jù),如果是gzip就解壓(以后可能要改成部分對(duì)比.contains()而不是全部對(duì)比) String contentEncoding = conn.getHeaderField("content-encoding"); if((contentEncoding != null)&&(contentEncoding.equals("gzip"))){ is = new GZIPInputStream(conn.getInputStream()); }else{ is = conn.getInputStream(); } in = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; while ((line = in.readLine()) != null) { result.append(line); System.out.println(line); } } else { System.out.println("ResponseCode is an error code:" + conn.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } } return result.toString(); } public String doGet(String URL) { HttpURLConnection conn = null; InputStream is = null; BufferedReader br = null; StringBuilder result = new StringBuilder(); try { // 創(chuàng)建遠(yuǎn)程url連接對(duì)象 URL url = new URL(URL); // 通過(guò)遠(yuǎn)程url連接對(duì)象打開(kāi)一個(gè)連接,強(qiáng)轉(zhuǎn)成HTTPURLConnection類 conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // 設(shè)置連接超時(shí)時(shí)間和讀取超時(shí)時(shí)間 conn.setConnectTimeout(15000); conn.setReadTimeout(60000); conn.setRequestProperty("accept-encoding","gzip, deflate, br"); conn.setRequestProperty("User-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36 Edg/98.0.1108.62"); // 發(fā)送請(qǐng)求 conn.connect(); // 通過(guò)conn取得輸入流,并使用Reader讀取 if (200 == conn.getResponseCode()) { // 獲取響應(yīng)頭content-encoding數(shù)據(jù),如果是gzip就解壓(以后可能要改成部分對(duì)比.contains()而不是全部對(duì)比) String contentEncoding = conn.getHeaderField("content-encoding"); if((contentEncoding != null)&&(contentEncoding.equals("gzip"))){ is = new GZIPInputStream(conn.getInputStream()); }else{ is = conn.getInputStream(); } br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; while ((line = br.readLine()) != null) { result.append(line); System.out.println(line); } } else { System.out.println("ResponseCode is an error code:" + conn.getResponseCode()); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } if (is != null) { is.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } conn.disconnect(); } return result.toString(); } public static void main(String[] args) { System.out.println(new HttpURLConnectionTools().doGet("https://api.66mz8.com/api/weather.php?location=%E5%8C%97%E4%BA%AC")); System.out.println(new HttpURLConnectionTools().doGet("http://api.wpbom.com/api/neran.php")); } }
以上就是Java使用GZIP壓縮導(dǎo)致HTTP請(qǐng)求返回亂碼問(wèn)題解決的詳細(xì)內(nèi)容,更多關(guān)于Java GZIP壓縮HTTP返回亂碼的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
簡(jiǎn)單的用java實(shí)現(xiàn)讀/寫文本文件的示例
同時(shí)也展示了如果從輸入流中讀出來(lái)內(nèi)容寫入輸出流中(僅限文本流) 三個(gè)例子可以獨(dú)立存在,所以根據(jù)需要只看其中一個(gè)就行了。2008-07-07Intellj Idea中的maven工程Java文件顏色不對(duì),未被識(shí)別的解決
這篇文章主要介紹了Intellj Idea中的maven工程Java文件顏色不對(duì),未被識(shí)別的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08Maven直接依賴、間接依賴、依賴沖突、依賴仲裁的實(shí)現(xiàn)
本文主要介紹了Maven直接依賴、間接依賴、依賴沖突、依賴仲裁的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-09-09SpringBoot中實(shí)現(xiàn)Redis緩存預(yù)熱
緩存預(yù)熱是一種在系統(tǒng)啟動(dòng)后,但在實(shí)際使用前將數(shù)據(jù)加載到緩存中的技術(shù),本文主要來(lái)和大家一起探討如何在Spring Boot應(yīng)用程序中實(shí)現(xiàn)Redis緩存預(yù)熱,以確保系統(tǒng)在處理請(qǐng)求前就已經(jīng)處于最佳狀態(tài),感興趣的可以了解下2023-11-11深入淺析Netty 在 Dubbo 中是如何應(yīng)用的
國(guó)內(nèi)知名框架 Dubbo 底層使用的是 Netty 作為網(wǎng)絡(luò)通信,那么內(nèi)部到底是如何使用的呢?今天通過(guò)本文給大家詳細(xì)講解,對(duì)Netty 在 Dubbo中應(yīng)用相關(guān)知識(shí)感興趣的朋友跟隨小編一起看看吧2020-05-05