在java中检索压缩与未压缩wcf响应的大小

时间:2014-08-11 21:15:05

标签: android

我想从压缩大小(gzip)和未压缩大小的.NET wcf web中检索响应的大小,以计算压缩率。 如何获得响应的压缩大小和未压缩大小?

这是我的Android java代码:

protected String doInBackground(String... urls) {
    DefaultHttpClient client = new DefaultHttpClient();
    client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
    String line = "";
    StringBuilder result = new StringBuilder();
    Boolean ResponseIsCompressed = false;
    BufferedReader rd;
    InputStreamReader reader = null;
    String charset = "UTF-8"; // You should determine it based on response header.
    try {
        URL url= new URL(urls[0]);
        HttpGet request = new HttpGet(url.toString());
        request.setHeader("Accept", "application/json");
        request.setHeader("Accept-Encoding", "gzip");
        request.setHeader("Content-type", "application/json");

        //get the response
        HttpResponse response = client.execute(request);
        StatusLine statusline =  response.getStatusLine();
        if (statusline.getStatusCode() != 200)
            throw new Exception(statusline.getReasonPhrase());

        HttpEntity entity = response.getEntity();
        if(entity.getContentLength() != 0) {
            // stream reader object

            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase("gzip")) {
                        ResponseIsCompressed = true;
                        break;
                    }
                }
            }
            if (ResponseIsCompressed) {
                InputStream gzippedResponse = response.getEntity().getContent();
                InputStream ungzippedResponse = new GZIPInputStream(gzippedResponse);
                reader = new InputStreamReader(ungzippedResponse, charset);
                rd = new BufferedReader(reader);
            }
            else {
                rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            }
            while((line = rd.readLine()) != null) {
                result.append((line));
            }
        }
    } catch (Exception e) {
        this.exception = e;
        return null;
    }
    return result.toString();
}

0 个答案:

没有答案