otak info official Logo   
OTAK.INFO
Personal Blog

Hariyanto Lim

정길상 / 鄭吉祥
Home   Last Posts  
 
Please login to see more topics and discussion categories.
 
goto main category list >> Software programming >> Android

Title : Customize Volley StringRequest to support gzip compression
Total Reply : 0
Total View : 2137


Harry
Harry
Total thread: 131
Total reply: 50

Post #165
Customize Volley StringRequest to support gzip compression
public interface StringRequestCallback {
  // 20150313 : added a new parameter "url" for debugging error
  public void onReceived(String url, boolean success, String response, String error);
}
public static void getString(final String url, final StringRequestCallback cb) {
  LogHelper.d(TAG, "getString(url: " + url + ", StringRequestCallback)");

  StringRequest sr = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
      StringRequestCallback mCB = cb;
      String sUrl = url;

      @Override
      public void onResponse(String response) {
        int iResponseLength = response == null ? 0 : response.trim().length();
        if(iResponseLength > 0) {
          LogHelper.d(TAG, "getString(...).onResponse(String response), response length: " + iResponseLength);
        } else {
          LogHelper.e(TAG, "getString(...).onResponse(String response), response is NULL or empty, url: " + sUrl);
        }

        if(mCB != null) {
          mCB.onReceived(sUrl, true, response, null);
        }
      }
    }
    , new Response.ErrorListener() {
      StringRequestCallback mCB = cb;
      String sUrl = url;

      @Override
      public void onErrorResponse(VolleyError error) {
        LogHelper.e(TAG, "### getString(...).onErrorResponse(VolleyError) : " + error.toString());
        if(mCB != null) {
          // 20150824 : is it 404 (not exist) page ???
          // we need to check whether need to RETRY or not
          if(error != null
              && error.networkResponse != null
              && error.networkResponse.statusCode == 404) {
            mCB.onReceived(sUrl, false, null, "404");
          } else {
            mCB.onReceived(sUrl, false, null, error.getLocalizedMessage());
          }
        }
      }
    }
  ) {
    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
      LogHelper.d(TAG, "getString(..).parseNetworkResponse(NetworkResponse)");

      String result = null;
      try {

        String contentEncoding = null;
        boolean NEED_TO_DECOMPRESS = false;
        if(USE_GZIP_COMPRESSION) {
          if(response != null && response.headers != null) {
            contentEncoding = response.headers.get(CONTENT_ENCODING_KEY);
            if(contentEncoding != null && contentEncoding.toLowerCase(Locale.US).contains(ACCEPT_ENCODING_VALUE)) {
              NEED_TO_DECOMPRESS = true;
            }
          }
        }
        LogHelper.d(TAG, "getString(..).parseNetworkResponse(NetworkResponse), " + CONTENT_ENCODING_KEY + ": " + contentEncoding);

        if(NEED_TO_DECOMPRESS) {
          result = decompressGZip(response.data);
        } else {
          LogHelper.d(TAG, "getString(..).parseNetworkResponse(NetworkResponse), no compression");
          result = new String(response.data, encodingUTF);
        }
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }

      return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
      //LogHelper.d(TAG, "getString(...).getHeaders() *** ");

      Map<String, String> header = setDefaultUserAgent(super.getHeaders());

      // 20150824 : Harry implement support for gzip compression
      if(USE_GZIP_COMPRESSION) {
        if (header != null) {
          header.put(ACCEPT_ENCODING_KEY, ACCEPT_ENCODING_VALUE);
        }
      }

      return header;
    }
  };

  // Wait 10 seconds and don't retry more than ONCE
  sr.setRetryPolicy(new DefaultRetryPolicy(
      (int) TimeUnit.SECONDS.toMillis(10)
      , 0 //DefaultRetryPolicy.DEFAULT_MAX_RETRIES
      , 0 //DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
  ));
  HVolleyImageCacheSingleton.getInstance().getRequestQueue().add(sr);

  //return sr;
}

private static String decompressGZip(byte[] compressedData) {

  if(compressedData == null || compressedData.length < 1) {
    LogHelper.e(TAG, "decompressGZip(byte[] compressedData), compressedData is null or empty");
    return null;
  }
  LogHelper.d(TAG, "decompressGZip(byte[] compressedData), compressedData length : " + compressedData.length);

  int compressedLength = 0;
  String output = "";
  try {
    GZIPInputStream gStream = new GZIPInputStream(new ByteArrayInputStream(compressedData));
    InputStreamReader reader = new InputStreamReader(gStream);
    BufferedReader in = new BufferedReader(reader);
    String read;
    while ((read = in.readLine()) != null) {
      output += read;

      compressedLength += read.length();
    }
    reader.close();
    in.close();
    gStream.close();
  } catch (IOException e) {
    LogHelper.e(TAG, "decompressGZip(byte[] compressedData), IOException: " + e.getLocalizedMessage());
    return null;
  }

  LogHelper.d(TAG, "decompressGZip(byte[] compressedData), compressed length: " + compressedLength + ", decompressed length: " + output.length());

  return output;
}

private static final boolean USE_GZIP_COMPRESSION = true;
private static final String ACCEPT_ENCODING_KEY = "Accept-Encoding";
private static final String CONTENT_ENCODING_KEY = "Content-Encoding";
private static final String ACCEPT_ENCODING_VALUE = "gzip";//,deflate";
Falling in love with the world

Write : 2015-08-25 08:55:58

If you want to create a new reply then please login first.



www.OTAK.INFO
Since 19 January 2007
Page hit : 664,214

Code update 24th June 2013
Brain is a very capable to solve big problems
but requires constant reminders about how to.
peace bird