0

I'm trying to get HttpResponseCache to cache responses to requests that include an "Authorization" header. I'm including this header because the API I am calling uses basic authentication.

HttpUrlConnection connection = initialiseConnection();
String usernameAndPasswordString = Base64.encodeToString(String.format("%s:%s", username, password).getBytes(), Base64.NO_WRAP);
connection.setRequestProperty("Authorization", String.format("basic %s", usernameAndPasswordString));`

To test this, I'm making the request with WiFi turned on. I'm then turning off WiFi and data and making the request again. I then get a FileNotFoundException when trying to read the response body.

InputStream inputStream = new BufferedInputStream(connection.getInputStream());

If I do the same thing but without the "Authorization" header (to an app on a different server that doesn't use basic auth), my code is able to read the response from the cache.

I am aware that an HTTP cache is not meant to cache a response that was the result of a request including an "Authorization" header, but does that mean that I just can't cache any responses from this server without writing my own cache? Is there any known way around this or to override this behaviour in HttpUrlConnection / HttpResponseCache?

Thanks in advance!

Glenn Porter
  • 536
  • 6
  • 18

1 Answers1

2

I managed to get to the bottom of this by going through the source code of HttpResponseCache (via https://github.com/candrews/HttpResponseCache, a custom version of the class by candrews taken from the Android source :) ). Including "public", "must-revalidate" or "s-maxage" directives in the Cache-Control header of the response will allow caching by HttpResponseCache even if the Authorization header was included in the request.

Glenn Porter
  • 536
  • 6
  • 18