use of okhttp3.Response in project kickmaterial by byoutline.
the class KickMaterialRequestInterceptor method intercept.
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
HttpUrl.Builder urlBuilder = original.url().newBuilder();
addBasicHeaders(urlBuilder);
String accessToken = accessTokenProvider.get();
if (!TextUtils.isEmpty(accessToken)) {
urlBuilder.addQueryParameter("oauth_token", accessToken);
}
HttpUrl newUrl = urlBuilder.build();
Request newRequest = original.newBuilder().url(newUrl).build();
return chain.proceed(newRequest);
}
use of okhttp3.Response in project GeekNews by codeestX.
the class HttpModule method provideClient.
@Singleton
@Provides
OkHttpClient provideClient(OkHttpClient.Builder builder) {
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
builder.addInterceptor(loggingInterceptor);
}
File cacheFile = new File(Constants.PATH_CACHE);
Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
Interceptor cacheInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!SystemUtil.isNetworkConnected()) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
}
Response response = chain.proceed(request);
if (SystemUtil.isNetworkConnected()) {
int maxAge = 0;
// 有网络时, 不缓存, 最大保存时长为0
response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader("Pragma").build();
} else {
// 无网络时,设置超时为4周
int maxStale = 60 * 60 * 24 * 28;
response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
}
return response;
}
};
// Interceptor apikey = new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// request = request.newBuilder()
// .addHeader("apikey",Constants.KEY_API)
// .build();
// return chain.proceed(request);
// }
// }
// 设置统一的请求头部参数
// builder.addInterceptor(apikey);
//设置缓存
builder.addNetworkInterceptor(cacheInterceptor);
builder.addInterceptor(cacheInterceptor);
builder.cache(cache);
//设置超时
builder.connectTimeout(10, TimeUnit.SECONDS);
builder.readTimeout(20, TimeUnit.SECONDS);
builder.writeTimeout(20, TimeUnit.SECONDS);
//错误重连
builder.retryOnConnectionFailure(true);
return builder.build();
}
use of okhttp3.Response in project buck by facebook.
the class ArtifactCaches method createHttpArtifactCache.
private static ArtifactCache createHttpArtifactCache(HttpCacheEntry cacheDescription, final String hostToReportToRemote, final BuckEventBus buckEventBus, ProjectFilesystem projectFilesystem, ListeningExecutorService httpWriteExecutorService, ArtifactCacheBuckConfig config, NetworkCacheFactory factory, boolean distributedBuildModeEnabled) {
// Setup the default client to use.
OkHttpClient.Builder storeClientBuilder = new OkHttpClient.Builder();
storeClientBuilder.networkInterceptors().add(chain -> chain.proceed(chain.request().newBuilder().addHeader("X-BuckCache-User", stripNonAscii(System.getProperty("user.name", "<unknown>"))).addHeader("X-BuckCache-Host", stripNonAscii(hostToReportToRemote)).build()));
int timeoutSeconds = cacheDescription.getTimeoutSeconds();
setTimeouts(storeClientBuilder, timeoutSeconds);
storeClientBuilder.connectionPool(new ConnectionPool(/* maxIdleConnections */
(int) config.getThreadPoolSize(), /* keepAliveDurationMs */
config.getThreadPoolKeepAliveDurationMillis(), TimeUnit.MILLISECONDS));
// The artifact cache effectively only connects to a single host at a time. We should allow as
// many concurrent connections to that host as we allow threads.
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequestsPerHost((int) config.getThreadPoolSize());
storeClientBuilder.dispatcher(dispatcher);
final ImmutableMap<String, String> readHeaders = cacheDescription.getReadHeaders();
final ImmutableMap<String, String> writeHeaders = cacheDescription.getWriteHeaders();
// If write headers are specified, add them to every default client request.
if (!writeHeaders.isEmpty()) {
storeClientBuilder.networkInterceptors().add(chain -> chain.proceed(addHeadersToBuilder(chain.request().newBuilder(), writeHeaders).build()));
}
OkHttpClient storeClient = storeClientBuilder.build();
// For fetches, use a client with a read timeout.
OkHttpClient.Builder fetchClientBuilder = storeClient.newBuilder();
setTimeouts(fetchClientBuilder, timeoutSeconds);
// If read headers are specified, add them to every read client request.
if (!readHeaders.isEmpty()) {
fetchClientBuilder.networkInterceptors().add(chain -> chain.proceed(addHeadersToBuilder(chain.request().newBuilder(), readHeaders).build()));
}
fetchClientBuilder.networkInterceptors().add((chain -> {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), buckEventBus)).build();
}));
OkHttpClient fetchClient = fetchClientBuilder.build();
HttpService fetchService;
HttpService storeService;
switch(config.getLoadBalancingType()) {
case CLIENT_SLB:
HttpLoadBalancer clientSideSlb = config.getSlbConfig().createClientSideSlb(new DefaultClock(), buckEventBus, new CommandThreadFactory("ArtifactCaches.HttpLoadBalancer", SLB_THREAD_PRIORITY));
fetchService = new RetryingHttpService(buckEventBus, new LoadBalancedService(clientSideSlb, fetchClient, buckEventBus), config.getMaxFetchRetries());
storeService = new LoadBalancedService(clientSideSlb, storeClient, buckEventBus);
break;
case SINGLE_SERVER:
URI url = cacheDescription.getUrl();
fetchService = new SingleUriService(url, fetchClient);
storeService = new SingleUriService(url, storeClient);
break;
default:
throw new IllegalArgumentException("Unknown HttpLoadBalancer type: " + config.getLoadBalancingType());
}
String cacheName = cacheDescription.getName().map(input -> "http-" + input).orElse("http");
boolean doStore = cacheDescription.getCacheReadMode().isDoStore();
return factory.newInstance(NetworkCacheArgs.builder().setThriftEndpointPath(config.getHybridThriftEndpoint()).setCacheName(cacheName).setRepository(config.getRepository()).setScheduleType(config.getScheduleType()).setFetchClient(fetchService).setStoreClient(storeService).setDoStore(doStore).setProjectFilesystem(projectFilesystem).setBuckEventBus(buckEventBus).setHttpWriteExecutorService(httpWriteExecutorService).setErrorTextTemplate(cacheDescription.getErrorMessageFormat()).setDistributedBuildModeEnabled(distributedBuildModeEnabled).build());
}
use of okhttp3.Response in project buck by facebook.
the class HttpArtifactCache method storeImpl.
@Override
protected void storeImpl(ArtifactInfo info, final Path file, final Finished.Builder eventBuilder) throws IOException {
// Build the request, hitting the multi-key endpoint.
Request.Builder builder = new Request.Builder();
final HttpArtifactCacheBinaryProtocol.StoreRequest storeRequest = new HttpArtifactCacheBinaryProtocol.StoreRequest(info, new ByteSource() {
@Override
public InputStream openStream() throws IOException {
return projectFilesystem.newFileInputStream(file);
}
});
eventBuilder.getStoreBuilder().setRequestSizeBytes(storeRequest.getContentLength());
// Wrap the file into a `RequestBody` which uses `ProjectFilesystem`.
builder.put(new RequestBody() {
@Override
public MediaType contentType() {
return OCTET_STREAM_CONTENT_TYPE;
}
@Override
public long contentLength() throws IOException {
return storeRequest.getContentLength();
}
@Override
public void writeTo(BufferedSink bufferedSink) throws IOException {
StoreWriteResult writeResult = storeRequest.write(bufferedSink.outputStream());
eventBuilder.getStoreBuilder().setArtifactContentHash(writeResult.getArtifactContentHashCode().toString());
}
});
// Dispatch the store operation and verify it succeeded.
try (HttpResponse response = storeClient.makeRequest("/artifacts/key", builder)) {
final boolean requestFailed = response.statusCode() != HttpURLConnection.HTTP_ACCEPTED;
if (requestFailed) {
reportFailure("store(%s, %s): unexpected response: [%d:%s].", response.requestUrl(), info.getRuleKeys(), response.statusCode(), response.statusMessage());
}
eventBuilder.getStoreBuilder().setWasStoreSuccessful(!requestFailed);
}
}
use of okhttp3.Response in project buck by facebook.
the class HttpArtifactCacheTest method testFetchMetadata.
@Test
public void testFetchMetadata() throws Exception {
Path output = Paths.get("output/file");
final String data = "test";
final RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
final ImmutableMap<String, String> metadata = ImmutableMap.of("some", "metadata");
argsBuilder.setFetchClient(withMakeRequest(((path, requestBuilder) -> {
Request request = requestBuilder.url(SERVER + path).build();
Response response = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(HttpURLConnection.HTTP_OK).body(createResponseBody(ImmutableSet.of(ruleKey), metadata, ByteSource.wrap(data.getBytes(Charsets.UTF_8)), data)).build();
return new OkHttpResponseWrapper(response);
})));
HttpArtifactCache cache = new HttpArtifactCache(argsBuilder.build());
CacheResult result = cache.fetch(ruleKey, LazyPath.ofInstance(output));
assertEquals(CacheResultType.HIT, result.getType());
assertEquals(metadata, result.getMetadata());
cache.close();
}
Aggregations