Home >Backend Development >PHP Tutorial >Gzip compression is used in the transmission of json data in the android interface

Gzip compression is used in the transmission of json data in the android interface

WBOY
WBOYOriginal
2016-07-29 09:13:431641browse

<span style="font-size:18px;">当前android访问接口传输数据多使用json格式(简单易解析跨平台),为了节省带宽和传输时间服务器往往会在传输前进行gzip压缩,下面是几个需要注意的地方。</span>

1. For PHP servers, when accessing the interface, you must bring the parameters Accept-Encoding: gzip, deflate in the header, otherwise even if gzip compression is done in the background, real compression will not be performed.

2. If the server gzip compresses the data, then the data needs to be gzip decompressed before the ap obtains the data:

<span style="font-size:18px;">public String getResponseBodyAsString(HttpResponse response) throws IO<strong>Exception</strong> {
        GZIPInputStream gzin;
        if (response.getEntity() != null) {
            Header header = response.getFirstHeader("Content-Encoding");
            if (header != null && header.getValue().toLowerCase().indexOf("gzip") != -1) {
                gzin = new GZIPInputStream(response.getEntity().getContent());
                InputStreamReader isr = new InputStreamReader(gzin, "UTF-8");
                BufferedReader br = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                String tmp;
                while ((tmp = br.readLine()) != null) {
                    sb.append(tmp);
                    sb.append("\r\n");
                }
                br.close();
                isr.close();
                return sb.toString();
            } else {
                // 否则正常返回
                return EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
            }
        } else {
            return null;
        }
    }</span>


The above introduces the use of gzip compression in the transmission of json data in the android interface, including Exception content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn