检测网站是否经过gzip压缩 http://tool.chinaz.com/Gzips/
Demo:点击按钮,查看打印日志判断服务器是否是进行过Gzip压缩
package com.loaderman.gzipdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.zip.GZIPInputStream; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startConnect(View view) { final String url = "http://www.loaderman.cn"; new Thread() { @Override public void run() { try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(2000); conn.setReadTimeout(2000); conn.setRequestMethod("GET"); conn.addRequestProperty("Accept-Encoding", "gzip");//表示本地客户端支持gzip压缩 conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { //判断服务器返回的是否是gzip String encoding = conn.getContentEncoding();//获取返回内容的压缩格式 String result; if ("gzip".equalsIgnoreCase(encoding)) { //服务器返回了gzip数据 //进行解压 //将网络的输入流包装成gzip输入流 GZIPInputStream in = new GZIPInputStream(conn.getInputStream()); System.out.println("返回的是gzip格式!!!"); result = streamToString(in); } else { result = streamToString(conn.getInputStream()); } System.out.println("返回结果:" + result); } } catch (IOException e) { e.printStackTrace(); } } }.start(); } public String streamToString(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 8]; int len = 0; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } out.flush(); String result = out.toString(); in.close(); out.close(); return result; } }
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.jcf.gzipdemo.MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="startConnect" android:text="开始连接网络"/> </RelativeLayout>