I have an issue with caching using OkHttpClient 2.0. It seems that the Response is ignoring the Cache-Control header completely. This is how I am setting up the client and the cache.
OkHttpClient client = new OkHttpClient();
cache = new Cache(new File(Session.getInstance().getContext().getCacheDir(),"http"), 10 * 1024 * 1024);
client.setCache(cache);
client.setCookieHandler(CookieHandler.getDefault());
client.setConnectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
client.setReadTimeout(SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
I believe that the cache directory is created correctly. This is what I see in journal in the /cache/http directory of my application.
libcore.io.DiskLruCache
1
201105
2
This is how I am creating the Request.
Request mRequest = new Request.Builder().url(mUrl).get().build();
Getting the response :
Response response = client.newCall(mRequest).execute();
When using curl, the headers as as follows.
< HTTP/1.1 200 OK
< Date: Fri, 27 Jun 2014 19:39:40 GMT
* Server Apache-Coyote/1.1 is not blacklisted
< Server: Apache-Coyote/1.1
< Cache-Control: no-transform, max-age=1800
< Content-Type: application/json
< Transfer-Encoding: chunked
The OKHttp response headers are as follows.
Connection:Keep-Alive
Content-Type:application/json
Date:Fri, 27 Jun 2014 18:58:30 GMT
Keep-Alive:timeout=5, max=100
OkHttp-Received-Millis:1403895511337
OkHttp-Selected-Protocol:http/1.1
OkHttp-Sent-Millis:1403895511140
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
The responses never get cached and the call client.getCache().getHitCount() always gives 0. Can someone please suggest what changes might be required here to make the cache work? Thanks.
Okay, the problem was all my get and post requests were using the Authorization Bearer xxxx header and http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html section 14.8 states that these requests can't be cached. The solution was to use s-maxage on the server instead of just max age according to this :
When a shared cache (see section 13.7) receives a request
containing an Authorization field, it MUST NOT return the
corresponding response as a reply to any other request, unless one
of the following specific exceptions holds:
If the response includes the "s-maxage" cache-control
directive, the cache MAY use that response in replying to a
subsequent request.
Are you reading the entire response body? OkHttp won't cache unless you consume the entire response.
I realize you solved your specific problem, but the symptom you describe has another cause.
When using the okhttp-urlconnection, caching doesn't kick in by default, unless we do this:
connection.setUseCaches(true)
(It should be on by default, but some library I was using was setting it to off)
Related
This may be a very basic question, but I've ran out of ideas.
Retrofit v2.4.0 is not sending the If-Modified-Since header, as a result caching is not working.
I'm polling the server several times a day to see if is there any updated data, hence the need for If-Modified-Since header. (push notifications may be implemented in a new release)
Based on this article, the setup is extremely easy: https://futurestud.io/tutorials/retrofit-2-activate-response-caching-etag-last-modified
I've read several related articles, but those were focused on the use-cases when the server's implementation was either inaccessible or it didn't send the headers. This is not my case. Those suggested the usage of networkInterceptors(). As the correct response headers are sent, I shouldn't need an interceptor (I guess).
Theoretically it should work.
Based on the response headers, it looks like that the server is correctly configured.
Here's the code:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);
Cache cache = new Cache(getApplication().getCacheDir(), 30 * 1024 * 1024);
httpClient = new OkHttpClient.Builder()
.cache(cache)
.addInterceptor(logging)
.build();
retrofit = new Retrofit.Builder()
.baseUrl("http://someserver:8080/")
.callbackExecutor(Executors.newSingleThreadExecutor())
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
Logs:
D/OkHttp: --> GET http://someserver:8080/model/modelId http/1.1
D/OkHttp: --> END GET
<-- 200 OK http://someserver:8080/model/modelId (23ms)
D/OkHttp: Cache-Control: private D/OkHttp: Content-Length:
3240854 D/OkHttp: Content-Type: application/octet-stream
D/OkHttp: Last-Modified: Mon, 14 May 2018 07:22:25 GMT
D/OkHttp: Date: Mon, 14 May 2018 09:03:50 GMT D/OkHttp: <-- END
HTTP
Please let me know what am I doing wrong.
Your server's cache configuration is incorrect. If you look at this article's Troubleshooting section you'll notice that it needs to be Cache-Control: private, must-revalidate.
This is how my request looks like:
ApiService apiService = retrofit.create(ApiService.class);
Observable<Response<UserUpdateResponse>> response = apiService.updateUser(Utils.getHeader(), object);
response.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::onSuccessUpdate,
this::onErr,
this::hideDialogLoading);
It's supposed to return 'code':'205' 'msg':'successfully update'. But when server response any code 201,202 (anything not 200) it will go to error.
Here is the Error.
java.net.ProtocolException: HTTP 205 had non-zero Content-Length: 121
So how do I prevent it from error, or how do I get error body? Thank you!.
HTTP response codes have a predefined definition and some have requirements that they must fullfill to be considered a valid HTTP payload. You cannot redefine what these codes mean for your application and expect well-implemented clients to accept it.
Looking specifically at HTTP 205 - Reset Content, which has the following requirement:
Since the 205 status code implies that no additional content will be provided, a server MUST NOT generate a payload in a 205 response.
Generally applications will just return HTTP 200 for all requests and include application-specific error codes in the payload. What you're doing does not make much sense.
So technically, I can get response 2xx. The problem was that server response body in response code 205 that suppose to be null (https://www.rfc-editor.org/rfc/rfc7231#section-6.3.6). So after set body null on server, android side works fine.
I have two services to generate and download PDF files. First there is POST (for hiding data) which save data in session, generate unique id and return it.
Second service is GET (param is unique id from POST) which remove id from session, generate PDF and returns it as stream. It looks like:
#RequestMapping(value = "/get", method = RequestMethod.GET)
#ResponseBody
public HttpEntity<byte[]> getData(
#ApiParam(name="hash", value="hash", required=true)
#RequestParam(value="hash", required = true) String hash,
#Context HttpServletResponse response) throws IOException {
Map reportData = reportsContext.getReportData(hash);
/*generate PDF here*/
return new HttpEntity<>(report.getContent(), getHeaders(report));
}
and getHeaders() is:
private HttpHeaders getHeaders(ReportData report) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.valueOf("application/pdf"));
headers.add("Content-Disposition", "attachment; filename=".concat(report.getTitle()).concat(".pdf"));
return headers;
}
It generally works fine on all browsers and systems but Android Chrome. First, I found out that Chrome on Android send two GETs (one from browser, second from download manager) - because hash was deleted, second GET thowed exception. Next step was saving generated stream in session (>.<) and returned it on second GET - despite returned streams was the same (when returning from getData()), second response is bad formated. I guess this is some kind of Spring issue, somehow it changes formatting.
There are initials of responses:
first GET:
HTTP/1.1 200 OK X-Powered-By: Express server: Apache-Coyote/1.1
content-disposition: attachment;
filename=operation_20052016.pdf content-type:
application/pdf content-length: 28626 date: Fri, 20 May 2016 07:51:08
GMT connection: close
%PDF-1.4 %âăĎÓ
second GET:
HTTP/1.1 200 OK X-Powered-By: Express server: Apache-Coyote/1.1
content-disposition: attachment;
filename=operation_20052016.pdf content-type:
application/pdf transfer-encoding: chunked date: Fri, 20 May 2016
07:51:13 GMT connection: close
2000 "JVBERi0xLjQKJeLj
------------ANSWER------------
Finally I put manually producible attribute, like:
request.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Sets.newHashSet(MediaType.valueOf("application/pdf")));
just before returning correct PDF. In case of error I dont set produces attribute so it take default value.
ANSWER:
Finally I put manually producible attribute, like:
request.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Sets.newHashSet(MediaType.valueOf("application/pdf")));
just before returning correct PDF. In case of error I dont set produces attribute so it take default value.
I have got an interesting exception when trying to upload data from Android client to AWS:
com.amazonaws.services.s3.model.AmazonS3Exception: x-amz-website-redirect-location header is not supported for this operation. (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument; Request ID: E3900749ACF1D979), S3 Extended Request ID: kFjMM7JVFSOxvaKlHgM0bVM5zKZAR/0K8qeMyt44vjvtMFcGk8CxY9gDBDs0sqWmr8r2jcCyENo=
The user located in China region and data is uploaded it under VPN (HongKong) to western bucket http://currentidmedia.s3-ap-southeast-1.amazonaws.com
More details about request below:
PUT http://currentidmedia.s3-ap-southeast-1.amazonaws.com / Headers: (Expect: 100-continue, Content-Type: application/octet-stream, Date: Fri, 05 Jun 2015 10:13:01 GMT+00:00, Content-Length: 0, User-Agent: aws-sdk-android/2.2.1 Linux/3.4.0-g8a80a0e Dalvik/2.1.0/0 en_US com.amazonaws.mobileconnectors.s3.transfermanager.TransferManager/2.2.1, x-amz-website-redirect-location: /storage/emulated/0/DCIM/Camera/IMG_20150601_153423.jpg, Accept-Encoding: identity, Authorization: AWS AKIAIYL3TJHYVMB4SFRQ:dAkmOJxaIe5viO5kNjz74I/UKSc=, )
Does it bug in SDk or I don't use it in proper way?
UPDATE:
// set up credentials
AWSCredentials awsCredentials = new BasicAWSCredentials(
awsMetadata.getAccountId(),
awsMetadata.getSecretKey()
);
// set up request
PutObjectRequest request = new PutObjectRequest(
awsMetadata.getBucketName(),
FileUtil.extractNameFromPath(mediaItem.getContentUri()),
mediaItem.getContentUri()
);
// perform request
TransferManager transferManager = new TransferManager(awsCredentials);
transferManager.getAmazonS3Client().setRegion(getRegionForMedia(awsMetadata));
transferManager.upload(request, listener);
The answer is I used PutObjectRequest in not correct way. It contains several constructors and if you pass String to content instead of File you setup redirection url instead of path to the data.
However after fix I got the same SSLException error for non-China bucket. I used it under VPN and without it. More details about request you can find below.
PUT https://currentidmedia.s3-ap-southeast-1.amazonaws.com / Headers: (Content-MD5: GI1M/hfrwwQHvHMBlmh/lA==, Expect: 100-continue, Content-Type: image/jpeg, Date: Sat, 06 Jun 2015 08:56:31 GMT+00:00, Content-Length: 2140572, User-Agent: aws-sdk-android/2.2.1 Linux/3.4.0-g8a80a0e Dalvik/2.1.0/0 en_US com.amazonaws.mobileconnectors.s3.transfermanager.TransferManager/2.2.1, Accept-Encoding: identity, Authorization: AWS AKIAIYL3TJHYVMB4SFRQ:fqWbHO6lBPsbI6lkcaHKhms8Hkw=, )
The x-amz-website-redirect-location metadata is for static website only. Static website has a different endpoint <bucket-name>.s3-website-<AWS-region>.amazonaws.com. See http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html for more information. Do you mind explaining the purpose of setting it? I'll see if there is an alternative.
Is there a proper explanation on how to add caching and ETAG/If-None-Match support to Retrofit+OkHttp?
I'm struggling to add Etag support on 2 projects, and at first I suspected that there might be an issue with HTTP headers, another project has everything set correctly and caching still doesn't work as expected.
Following are my attempts to make it work. Results show that caching seems to be working within the same instance of the application, but as soon as I restart - everything loads long again.
Also, in my logs I didn't see If-None-Match being added to a request, so I assume that server isn't aware of ETag and still recalculates the response completely.
Here are some code samples:
public class RetrofitHttpClient extends UrlConnectionClient
{
private OkUrlFactory generateDefaultOkUrlFactory()
{
OkHttpClient client = new com.squareup.okhttp.OkHttpClient();
try
{
Cache responseCache = new Cache(baseContext.getCacheDir(), SIZE_OF_CACHE);
client.setCache(responseCache);
}
catch (Exception e)
{
Logger.log(this, e, "Unable to set http cache");
}
client.setConnectTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
client.setReadTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS);
return new OkUrlFactory(client);
}
private final OkUrlFactory factory;
public RetrofitHttpClient()
{
factory = generateDefaultOkUrlFactory();
}
#Override
protected HttpURLConnection openConnection(retrofit.client.Request request) throws IOException
{
return factory.open(new URL(request.getUrl()));
}
}
Rest adapter is then created with FULL log level and a custom tag:
restAdapter = new RestAdapter.Builder()
.setClient(new RetrofitHttpClient())
.setEndpoint(Config.BASE_URL)
.setRequestInterceptor(new SignatureSetter())
.setConverter(new JacksonConverter(JsonHelper.getObjectMapper()))
.setLogLevel(RestAdapter.LogLevel.FULL)
.setLog(new AndroidLog("=NETWORK="))
.build();
I have a long request on the first screen of the app for testing.
When I open the app - it takes 7 seconds to complete the request. If I pause and resume the app - same request takes 250ms, clearly hitting the cache. If I close the app completely and restart - it again takes 7 seconds.
UPDATE:
As was suggested, I have used a custom Retrofit build and attached a LoggingInterceptor. Here's what I'm getting.
Received response for *** in 449,3ms
Date: Wed, 07 Jan 2015 09:02:23 GMT
Server: Apache
X-Powered-By: PHP/5.4.31
Access-Control-Allow-Credentials: true
Pragma:
Cache-Control: public, max-age=3600
X-Frame-Options: SAMEORIGIN
Etag: "hLxLRYztkinJAB453nRV7ncBSuU=-gzip"
Last-Modified: Wed, 24 Dec 2014 13:09:04 GMT
Vary: Accept-Encoding
Content-Encoding: gzip
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1420621288104
OkHttp-Received-Millis: 1420621288554
Sending request **** on Connection{****:80, proxy=DIRECT# hostAddress=**** cipherSuite=none protocol=http/1.1}
Accept: application/json;
Host: ****
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/2.2.0
Response is equal to described above
As you can see, no If-None-Match header is present in the next request.
I see this question keeps getting attention and as soon as there is no real answer I can pick from - I'm am providing my investigation on the topic and closing the thread for now.
The end result of investigation and some discussions in the retrofit and okhttp threads on GitHub was that there was supposedly an issue in OkHttp that could prevent If-None-Match tag being set for the outgoing requests.
The issue was supposed to be fixed in OkHttp 2.3, and I'm using 'supposed' here because I didn't yet test if it really works. The testing was difficult because I was using Retrofit, and Retrofit itself had to be updated to use the new version of OkHttp and add some new Interceptors support to be able to debug all headers that are set by OkHttp.
Related thread is here: https://github.com/square/okhttp/issues/831
I'm not sure if Retrofit was updated after that. Hopefully it was, so there is a good chance that issue is already fixed and Etag should properly work - just make sure you have latest versions of Retrofit and OkHttp.
I will try to test everything myself once I have time.
Using OkHttp interceptors will help you to diagnose the headers coming in & out of your application. The interceptors doc gives a code example of an interceptor that logs request & response headers on the network. You can use this as-is.
class LoggingInterceptor implements Interceptor {
#Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
logger.info(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
logger.info(String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
To hook it up to Retrofit, you'll need to get a pre-release snapshot of Retrofit. As of January, 2015, the currently-shipping versions of Retrofit don't participate in OkHttp's interceptors. There will be a release shortly that does, but it's not ready yet.
I was having a similar problem: OkHttp not hitting cache ever, even when the server was sending same ETAG.
My issue was SIZE_OF_CACHE. I was defining a very small size.
Try to increase it (something like 10 * 1024 * 1024 works for me)
Also you can explore /data/data//files/cache to see if there is actually something stored there