Skip to content

Commit 9e1f16b

Browse files
committed
Fix OkHttpConnector caching
1 parent c845846 commit 9e1f16b

2 files changed

Lines changed: 49 additions & 1 deletion

File tree

src/main/java/org/kohsuke/github/extras/OkHttpConnector.java

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,18 @@ public OkHttpConnector(OkUrlFactory urlFactory) {
4141
}
4242

4343
public HttpURLConnection connect(URL url) throws IOException {
44-
return urlFactory.open(url);
44+
HttpURLConnection urlConnection = urlFactory.open(url);
45+
if (urlFactory.client() != null && urlFactory.client().getCache() != null) {
46+
// By default OkHttp honors max-age, meaning it will use local cache
47+
// without checking the network within that time frame.
48+
// However, that can result in stale data being returned during that time so
49+
// we force network-based checking no matter how often the query is made.
50+
// OkHttp still automatically does ETag checking and returns cached data when
51+
// GitHub reports 304, but those do not count against rate limit.
52+
urlConnection.setRequestProperty("Cache-Control", "max-age=0");
53+
}
54+
55+
return urlConnection;
4556
}
4657

4758
/** Returns TLSv1.2 only SSL Socket Factory. */
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package org.kohsuke.github;
2+
3+
import com.squareup.okhttp.OkUrlFactory;
4+
import com.squareup.okhttp.Cache;
5+
import com.squareup.okhttp.OkHttpClient;
6+
import org.apache.commons.io.FileUtils;
7+
import org.kohsuke.github.extras.OkHttpConnector;
8+
9+
import java.io.File;
10+
import java.io.IOException;
11+
12+
/**
13+
* @author Liam Newman
14+
*/
15+
public abstract class OkHttpConnectorTest extends AbstractGitHubApiWireMockTest {
16+
17+
protected GitHubBuilder getGitHubBuilder() {
18+
OkHttpClient client = new OkHttpClient();
19+
20+
File cacheDir = new File("target/cache/" + baseFilesClassPath + "/" + githubApi.getMethodName());
21+
cacheDir.mkdirs();
22+
try {
23+
FileUtils.cleanDirectory(cacheDir);
24+
} catch (IOException e) {}
25+
Cache cache = new Cache(cacheDir, 100 * 1024L * 1024L);
26+
27+
client.setCache(cache);
28+
29+
return super.getGitHubBuilder()
30+
.withConnector(new OkHttpConnector(new OkUrlFactory(client)));
31+
}
32+
33+
// TODO: Show the same actions with Default, OkHttp, and OkHttp with Cache
34+
// Verify how each behaves
35+
36+
37+
}

0 commit comments

Comments
 (0)