package com.xt.hb.gis.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

public class CustomGetMethod {
    public static String getGzip(HttpResponse response) throws IOException {

        // For GZip response
        if (isGzip(response)) {
            InputStream is = response.getEntity().getContent();
            GZIPInputStream gzin = new GZIPInputStream(is);

            InputStreamReader isr = new InputStreamReader(gzin, "utf-8");
            java.io.BufferedReader br = new java.io.BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String tempbf;
            while ((tempbf = br.readLine()) != null) {
                sb.append(tempbf);
            }
            isr.close();
            gzin.close();
            return sb.toString();
        }
        else {
            return EntityUtils.toString(response.getEntity(), "utf-8");
        }

    }

    private static boolean isGzip(HttpResponse response) {
        if (response.containsHeader("Content-Encoding")) {
            Header[] hs = response.getHeaders("Content-Encoding");
            for (Header h : hs) {
                if (h.getValue().toLowerCase().indexOf("gzip") > -1) { return true; }
            }
        }
        return false;
    }

}
