HttpResponseCache work with Image but not Json

128 Views Asked by At

I'm trying to use HttpResponseCache to enable the response caching (for web requests) . In My application, I execute the request by UrlConnection with Loader and then I sent InputStream result to the Activity to show image or work with JsonObject. In my case, HttpResponseCache work with image's url and can show image when offline but with Json's Url, the inputstream result just work only online, it cannot show data when offline.


Loader Class:

public InputStream loadInBackground() {
    InputStream streamResult = null;
    HttpURLConnection conn = null;

    URL url = new URL(urlConnection);
    conn = (HttpURLConnection) url.openConnection();
    conn.setUseCaches(true);
    final InputStream finalStream = conn.getInputStream();
    streamResult = finalStream;
    ((Activity) context).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            ShowData(finalStream);
        }
    });
    return streamResult;
}

Activity:

@Override
public void ShowData(InputStream output) {
    if (output != null) {
            if (rbtImage.isChecked()) {
                bitmap = BitmapFactory.decodeStream(output);
            } else if (rbtJson.isChecked()) {
                try {
                    result = convertStreamToString(output);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }
}

After executed by Loader, I can show Image with that bitmap by Image's Url. But cannot show data with Json's Url when offline.

I try to use with:addRequestProperty("Cache-Control", "only-if-cached"); "max-stale", "max-age", "max-age=600, private, must-revalidate". But nothing work.

Please help me to know How to use HttpResponseCache with Json?

0

There are 0 best solutions below