program tip

Android : HTTP 통신은 "Accept-Encoding : gzip"을 사용해야합니다.

radiobox 2020. 8. 5. 08:05
반응형

Android : HTTP 통신은 "Accept-Encoding : gzip"을 사용해야합니다.


JSON 데이터를 요청하는 웹 서버와의 HTTP 통신이 있습니다. 이 데이터 스트림을으로 압축하고 싶습니다 Content-Encoding: gzip. Accept-Encoding: gzip내 HttpClient에서 설정할 수있는 방법이 있습니까? 여기에서gzip 볼 수 있듯이 Android 참조에서 검색 하면 HTTP와 관련된 내용이 표시되지 않습니다 .


연결에서 gzip으로 인코딩 된 데이터를 수락 할 수 있음을 나타내려면 http 헤더를 사용해야합니다. 예 :

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

그들은 HttpRequestInterceptorHttpResponseInterceptor를 사용 하고 있습니다.

요청 샘플 :

        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);
}

참고 URL : https://stackoverflow.com/questions/1573391/android-http-communication-should-use-accept-encoding-gzip

반응형