use of com.pushtorefresh.storio3.Interceptor in project okhttp by square.
the class HttpOverHttp2Test method connectionShutdownAfterHealthCheck.
/**
* This simulates a race condition where we receive a healthy HTTP/2 connection and just prior to
* writing our request, we get a GOAWAY frame from the server.
*/
@Test
public void connectionShutdownAfterHealthCheck() throws Exception {
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_END).setBody("ABC"));
server.enqueue(new MockResponse().setBody("DEF"));
OkHttpClient client2 = client.newBuilder().addNetworkInterceptor(new Interceptor() {
boolean executedCall;
@Override
public Response intercept(Chain chain) throws IOException {
if (!executedCall) {
// At this point, we have a healthy HTTP/2 connection. This call will trigger the
// server to send a GOAWAY frame, leaving the connection in a shutdown state.
executedCall = true;
Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute();
assertEquals("ABC", response.body().string());
// Wait until the GOAWAY has been processed.
RealConnection connection = (RealConnection) chain.connection();
while (connection.isHealthy(false)) ;
}
return chain.proceed(chain.request());
}
}).build();
Call call = client2.newCall(new Request.Builder().url(server.url("/")).build());
Response response = call.execute();
assertEquals("DEF", response.body().string());
assertEquals(0, server.takeRequest().getSequenceNumber());
assertEquals(0, server.takeRequest().getSequenceNumber());
}
use of com.pushtorefresh.storio3.Interceptor in project okhttp by square.
the class RealInterceptorChain method proceed.
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec, RealConnection connection) throws IOException {
if (index >= interceptors.size())
throw new AssertionError();
calls++;
// If we already have a stream, confirm that the incoming request will use it.
if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1) + " must retain the same host and port");
}
// If we already have a stream, confirm that this is the only call to chain.proceed().
if (this.httpCodec != null && calls > 1) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1) + " must call proceed() exactly once");
}
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec, connection, index + 1, request);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
// Confirm that the next interceptor made its required call to chain.proceed().
if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
throw new IllegalStateException("network interceptor " + interceptor + " must call proceed() exactly once");
}
// Confirm that the intercepted response isn't null.
if (response == null) {
throw new NullPointerException("interceptor " + interceptor + " returned null");
}
return response;
}
use of com.pushtorefresh.storio3.Interceptor in project Parse-SDK-Android by ParsePlatform.
the class ParseOkHttpClient method addExternalInterceptor.
/**
* For OKHttpClient, since it does not expose any interface for us to check the raw response
* stream, we have to use OKHttp networkInterceptors. Instead of using our own interceptor list,
* we use OKHttp inner interceptor list.
* @param parseNetworkInterceptor
*/
@Override
/* package */
void addExternalInterceptor(final ParseNetworkInterceptor parseNetworkInterceptor) {
OkHttpClient.Builder builder = okHttpClient.newBuilder();
builder.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(final Chain okHttpChain) throws IOException {
Request okHttpRequest = okHttpChain.request();
// Transfer OkHttpRequest to ParseHttpRequest
final ParseHttpRequest parseRequest = getParseHttpRequest(okHttpRequest);
// Capture OkHttpResponse
final Capture<Response> okHttpResponseCapture = new Capture<>();
final ParseHttpResponse parseResponse = parseNetworkInterceptor.intercept(new ParseNetworkInterceptor.Chain() {
@Override
public ParseHttpRequest getRequest() {
return parseRequest;
}
@Override
public ParseHttpResponse proceed(ParseHttpRequest parseRequest) throws IOException {
// Use OKHttpClient to send request
Request okHttpRequest = ParseOkHttpClient.this.getRequest(parseRequest);
Response okHttpResponse = okHttpChain.proceed(okHttpRequest);
okHttpResponseCapture.set(okHttpResponse);
return getResponse(okHttpResponse);
}
});
final Response okHttpResponse = okHttpResponseCapture.get();
// Ideally we should build newOkHttpResponse only based on parseResponse, however
// ParseHttpResponse does not have all the info we need to build the newOkHttpResponse, so
// we rely on the okHttpResponse to generate the builder and change the necessary info
// inside
Response.Builder newOkHttpResponseBuilder = okHttpResponse.newBuilder();
// Set status
newOkHttpResponseBuilder.code(parseResponse.getStatusCode()).message(parseResponse.getReasonPhrase());
// Set headers
if (parseResponse.getAllHeaders() != null) {
for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) {
newOkHttpResponseBuilder.header(entry.getKey(), entry.getValue());
}
}
// Set body
newOkHttpResponseBuilder.body(new ResponseBody() {
@Override
public MediaType contentType() {
if (parseResponse.getContentType() == null) {
return null;
}
return MediaType.parse(parseResponse.getContentType());
}
@Override
public long contentLength() {
return parseResponse.getTotalSize();
}
@Override
public BufferedSource source() {
// interceptor.
if (parseResponse.getContent() == null) {
return null;
}
return Okio.buffer(Okio.source(parseResponse.getContent()));
}
});
return newOkHttpResponseBuilder.build();
}
});
okHttpClient = builder.build();
}
use of com.pushtorefresh.storio3.Interceptor in project run-wallet-android by runplay.
the class IotaMsgCore method postConstruct.
/**
* added header for IRI
*/
private void postConstruct() {
final String nodeUrl = protocol + "://" + host + ":" + port;
// Create OkHttpBuilder
Authenticator auth = new Authenticator() {
@Nullable
@Override
public Request authenticate(Route route, okhttp3.Response response) throws IOException {
if (responseCount(response) >= 3) {
// If we've failed 3 times, give up. - in real life, never give up!!
return null;
}
String credential = Credentials.basic(uname, upassword);
return response.request().newBuilder().header("Authorization", credential).build();
}
};
final OkHttpClient client = new OkHttpClient.Builder().readTimeout(5000, TimeUnit.SECONDS).authenticator(auth).addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request newRequest;
newRequest = request.newBuilder().addHeader(X_IOTA_API_VERSION_HEADER_NAME, X_IOTA_API_VERSION_HEADER_VALUE).build();
return chain.proceed(newRequest);
}
}).connectTimeout(5000, TimeUnit.SECONDS).build();
// use client to create Retrofit service
final Retrofit retrofit = new Retrofit.Builder().baseUrl(nodeUrl).addConverterFactory(GsonConverterFactory.create()).client(client).build();
service = retrofit.create(IotaAPIService.class);
log.debug("Jota-API Java proxy pointing to node url: '{}'", nodeUrl);
}
use of com.pushtorefresh.storio3.Interceptor in project Awesome-WanAndroid by JsonChao.
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 = chain -> {
Request request = chain.request();
if (!CommonUtils.isNetworkConnected()) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
}
Response response = chain.proceed(request);
if (CommonUtils.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;
};
// 设置缓存
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);
// cookie认证
builder.cookieJar(new CookiesManager());
return builder.build();
}
Aggregations