use of okhttp3.Interceptor in project MVPArms by JessYanCoding.
the class WEApplication method getGlobeConfigModule.
/**
* app的全局配置信息封装进module(使用Dagger注入到需要配置信息的地方)
* GlobeHttpHandler是在NetworkInterceptor中拦截数据
* 如果想将请求参数加密,则必须在Interceptor中对参数进行处理,GlobeConfigModule.addInterceptor可以添加Interceptor
* @return
*/
@Override
protected GlobeConfigModule getGlobeConfigModule() {
return GlobeConfigModule.buidler().baseurl(Api.APP_DOMAIN).globeHttpHandler(new // 这里可以提供一个全局处理http响应结果的处理类,
GlobeHttpHandler() {
// 这里可以比客户端提前一步拿到服务器返回的结果,可以做一些操作,比如token超时,重新获取
@Override
public Response onHttpResultResponse(String httpResult, Interceptor.Chain chain, Response response) {
//重新请求token,并重新执行请求
try {
if (!TextUtils.isEmpty(httpResult)) {
JSONArray array = new JSONArray(httpResult);
JSONObject object = (JSONObject) array.get(0);
String login = object.getString("login");
String avatar_url = object.getString("avatar_url");
Timber.tag(TAG).w("result ------>" + login + " || avatar_url------>" + avatar_url);
}
} catch (JSONException e) {
e.printStackTrace();
return response;
}
//如果不需要返回新的结果,则直接把response参数返回出去
return response;
}
// 这里可以在请求服务器之前可以拿到request,做一些操作比如给request统一添加token或者header
@Override
public Request onHttpRequestBefore(Interceptor.Chain chain, Request request) {
// .build();
return request;
}
}).responseErroListener(new ResponseErroListener() {
// 用来提供处理所有错误的监听
// rxjava必要要使用ErrorHandleSubscriber(默认实现Subscriber的onError方法),此监听才生效
@Override
public void handleResponseError(Context context, Exception e) {
Timber.tag(TAG).w("------------>" + e.getMessage());
UiUtils.SnackbarText("net error");
}
}).build();
}
use of okhttp3.Interceptor in project okhttp by square.
the class RealCall method getResponseWithInterceptorChain.
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());
interceptors.add(retryAndFollowUpInterceptor);
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectInterceptor(client));
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors());
}
interceptors.add(new CallServerInterceptor(forWebSocket));
Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0, originalRequest);
return chain.proceed(originalRequest);
}
use of okhttp3.Interceptor in project retrofit by square.
the class CallTest method conversionProblemIncomingMaskedByConverterIsUnwrapped.
@Test
public void conversionProblemIncomingMaskedByConverterIsUnwrapped() throws IOException {
// MWS has no way to trigger IOExceptions during the response body so use an interceptor.
OkHttpClient client = //
new OkHttpClient.Builder().addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Response response = chain.proceed(chain.request());
ResponseBody body = response.body();
BufferedSource source = Okio.buffer(new ForwardingSource(body.source()) {
@Override
public long read(Buffer sink, long byteCount) throws IOException {
throw new IOException("cause");
}
});
body = ResponseBody.create(body.contentType(), body.contentLength(), source);
return response.newBuilder().body(body).build();
}
}).build();
Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).client(client).addConverterFactory(new ToStringConverterFactory() {
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return new Converter<ResponseBody, String>() {
@Override
public String convert(ResponseBody value) throws IOException {
try {
return value.string();
} catch (IOException e) {
// Some serialization libraries mask transport problems in runtime exceptions. Bad!
throw new RuntimeException("wrapper", e);
}
}
};
}
}).build();
Service example = retrofit.create(Service.class);
server.enqueue(new MockResponse().setBody("Hi"));
Call<String> call = example.getString();
try {
call.execute();
fail();
} catch (IOException e) {
assertThat(e).hasMessage("cause");
}
}
use of okhttp3.Interceptor in project okhttp by square.
the class CacheTest method networkInterceptorInvokedForConditionalGet.
@Test
public void networkInterceptorInvokedForConditionalGet() throws Exception {
server.enqueue(new MockResponse().addHeader("ETag: v1").setBody("A"));
server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));
// Seed the cache.
HttpUrl url = server.url("/");
assertEquals("A", get(url).body().string());
final AtomicReference<String> ifNoneMatch = new AtomicReference<>();
client = client.newBuilder().addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
ifNoneMatch.compareAndSet(null, chain.request().header("If-None-Match"));
return chain.proceed(chain.request());
}
}).build();
// Confirm the value is cached and intercepted.
assertEquals("A", get(url).body().string());
assertEquals("v1", ifNoneMatch.get());
}
use of okhttp3.Interceptor in project okhttp by square.
the class CacheTest method networkInterceptorNotInvokedForFullyCached.
@Test
public void networkInterceptorNotInvokedForFullyCached() throws Exception {
server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60").setBody("A"));
// Seed the cache.
HttpUrl url = server.url("/");
assertEquals("A", get(url).body().string());
// Confirm the interceptor isn't exercised.
client = client.newBuilder().addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
throw new AssertionError();
}
}).build();
assertEquals("A", get(url).body().string());
}
Aggregations