Android:HTTP通信は「Accept-Encoding:GZIP」を使用する必要があります
-
21-09-2019 - |
質問
JSONデータを要求するWebサーバーとのHTTP通信があります。このデータストリームを圧縮したいのですが Content-Encoding: gzip
. 。設定する方法はありますか? Accept-Encoding: gzip
私のhttpclientで?の検索 gzip
Androidでは、あなたが見ることができるように、HTTPに関連するものは何も表示されません ここ.
解決
HTTPヘッダーを使用して、接続がGZIPエンコードされたデータを受け入れることができることを示す必要があります。
HttpUriRequest request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip");
// ...
httpClient.execute(request);
コンテンツのエンコードの応答を確認してください:
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
他のヒント
APIレベル8以上を使用している場合 androidhttpclient.
次のようなヘルパーメソッドがあります。
public static InputStream getUngzippedContent (HttpEntity entity)
と
public static void modifyRequestToAcceptGzipResponse (HttpRequest request)
はるかに簡潔なコードにつながる:
AndroidHttpClient.modifyRequestToAcceptGzipResponse( request );
HttpResponse response = client.execute( request );
InputStream inputStream = AndroidHttpClient.getUngzippedContent( response.getEntity() );
このリンクのコードのサンプルはもっと興味深いと思います。clientGzipContentCompression.java
彼らは使用しています httpRequestInterceptor と httpresponseinterceptor
リクエストのサンプル:
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
}
});
回答のサンプル:
httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
私はGZIPを使用していませんが、あなたの入力ストリームを使用する必要があると思います HttpURLConnection
また HttpResponse
なので GZIPInputStream
, 、そして特定の他のクラスではありません。
私の場合、それは次のようでした:
URLConnection conn = ...;
InputStream instream = conn.getInputStream();
String encodingHeader = conn.getHeaderField("Content-Encoding");
if (encodingHeader != null && encodingHeader.toLowerCase().contains("gzip"))
{
instream = new GZIPInputStream(instream);
}
所属していません StackOverflow