首頁 > 軟體

Java使用GZIP壓縮導致HTTP請求返回亂碼問題解決

2022-06-17 18:03:34

原因

用Java呼叫雪球的API,結果返回的是亂碼,一番研究後發現是因為返回的資料使用了GZIP壓縮,需要先解壓才能得到正確資料。

思路

使用了GZIP壓縮的資料在響應頭裡會有一項名為content-encoding的引數,值為gzip。

Java中可以使用.getHeaderField()讀取響應頭的引數。

如果沒有這項引數,會返回null。

解決方法

用.getHeaderField("content-encoding")讀取content-encoding引數的值。

如果值不為空,通過值判斷是否用了gzip壓縮。

使用了gzip就解壓,沒用就不處理。

程式碼

關鍵部分

// 獲取響應頭content-encoding資料,如果是gzip就解壓(以後可能要改成部分對比.contains()而不是全部對比)
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");
            // 傳送POST請求必須設定為true
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 設定連線超時時間和讀取超時時間
            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()) {
                // 獲取響應頭content-encoding資料,如果是gzip就解壓(以後可能要改成部分對比.contains()而不是全部對比)
                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 {
            // 建立遠端url連線物件
            URL url = new URL(URL);
            // 通過遠端url連線物件開啟一個連線,強轉成HTTPURLConnection類
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // 設定連線超時時間和讀取超時時間
            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");
            // 傳送請求
            conn.connect();
            // 通過conn取得輸入流,並使用Reader讀取
            if (200 == conn.getResponseCode()) {
                // 獲取響應頭content-encoding資料,如果是gzip就解壓(以後可能要改成部分對比.contains()而不是全部對比)
                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壓縮導致HTTP請求返回亂碼問題解決的詳細內容,更多關於Java GZIP壓縮HTTP返回亂碼的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com