Android HttpURLConnection設定Accept-Encoding爲gzip的時候返回數據出現亂碼

設定的位置是這個方法,攔截請求,然後在WebView的請求頭中加自己的Header 

 mWebView.setWebViewClient(new WebViewClient() {

            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
}
});

下面是設置請求頭的代碼如下 

URL url = new URL(request.getUrl().toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Encoding","gzip,deflate");
connection.getOutputStream().write(mPostBytes);
return new WebResourceResponse("text/html",connection.getHeaderField("encoding"), connection.getInputStream());

本身HttpURLConnection是默認支持自動Gzip壓縮與配套解壓縮處理的,但是如果手動設置了下面這句話,自動的處理就不靈了,也就是說,請求頭手動加了這個,那麼返回的數據也要手動解壓縮。要麼就不要手動加這個。

connection.setRequestProperty(Constants.REQUEST_PROPERTY_ACCEPT_ENCODING,"gzip,deflate");

手動加解壓縮的方法也很簡單,如下圖:

//改之前:
return new WebResourceResponse("text/html",connection.getHeaderField("encoding"), connection.getInputStream());
//改之後:
return new WebResourceResponse("text/html",connection.getHeaderField("encoding"), new GZIPInputStream(connection.getInputStream()));

利用的是【GZIPInputStream】這個類。

另外,如果服務器本身根本不支持Gzip的情況下,即使你怎麼手動配置gzip請求頭都無所謂,因爲服務器根本不支持,怎麼樣都是返回的未壓縮的純文本,是不會出現問題的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章