DefaultHttpClient 使用GZIPInputStream解壓縮

DefaultHttpClient 使用GZIPInputStream解壓縮 當瀏覽器訪問網站時,有可能瀏覽器返回的消息頭中帶有 Content-Encoding:gzip,代表服務器返回的消息通過gzip壓縮,這麼作是爲了節省流量,瀏覽器拿到gzip壓縮後的http包,對其進行解壓縮,再渲染出來。在使用apache提供的 DefaultHttpClient操做http請求時,可使用 GZIPInputStream對gzip壓縮過的數據包進行解壓縮。android sdk進行網絡編程時,也可使用這種方法。簡單代碼以下:
DefaultHttpClient httpClient =  new DefaultHttpClient();
    //dns探測源ip
    String[] dnsIps = {"jsdx", "yndx", "bjdx", "bjlt", "sclt", "shlt", "gg"};

    for(String ip : dnsIps)
    {
        HttpPost post = new HttpPost("http://webscan.360.cn/tools/dnsInfo.php");
        post.addHeader("Referer", "http://webscan.360.cn/tools/dnslookup");
        post.addHeader("X-Requested-With", "XMLHttpRequest");
        post.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
        post.addHeader("Accept", "*/*");
        post.addHeader("Accept-Encoding", "gzip, deflate");
        post.addHeader("Accept-Language", "zh-cn,en-us;q=0.7,en;q=0.3");
        post.addHeader("Pragma", "no-cache");
        post.addHeader("Cache-Control", "no-cache");

        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("dns_ip", ip));
        params.add(new BasicNameValuePair("domain_name", domain));
        params.add(new BasicNameValuePair("dns_type", "A"));
        UrlEncodedFormEntity formEntity = null;
        HttpResponse response = null;
        String responseHtml = null;
        try
        {
            formEntity = new UrlEncodedFormEntity(params, "utf-8");
            post.setEntity(formEntity);
            response = httpClient.execute(post);
            InputStream is= response.getEntity().getContent();
          is= new GZIPInputStream(is);
          BufferedReader br = new BufferedReader(new InputStreamReader(is));
          String line = null;
          StringBuffer sb = new StringBuffer();
            while((line = br.readLine())!=null) {
             sb.append(line);
            }
            responseHtml = sb.toString();

        } catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
相關文章
相關標籤/搜索