在项目中可能会遇到这样的需求,我们在进行网络请求时,可能会遇到各种超时或者连接不上的情况。为了方便排查问题是出在前端还是在后台,要设计出一套方案解决这个问题,最简单的方案就是在请求的最后面增加公共参数或者请求头来作为请求的唯一ID(这里以时间戳为例)。其实该参数在后台是不会接收用来实际使用的,所有请求会在缓存中记录下来。当出现网络请求超时等情况时前端通过显示请求的时间戳,后台查询缓存中的日志如果包含该条日志,说明是后台问题,不包含则是前台的问题。下面来看看如何添加吧!
传统的okHttp中添加公共求情参数或者请求头,但是结果拿不到请求参数
这种方式的添加是可以添加公共的参数和请求头,但是达不到我们的需求。
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(MODIFIED_INTERCEPTOR)
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
public static Interceptor MODIFIED_INTERCEPTOR = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
//以参数的方式添加
//重定向URL
HttpUrl modifiedUrl = request.url().newBuilder()
.addQueryParameter("timestamp", Long.toHexString(System.currentTimeMillis()))
.build();
//请求重定向
Request newRequest = request.newBuilder().url(modifiedUrl).build();
/*
//以头文件的方式添加
Request newRequest = request.newBuilder()
.addHeader("timestamp", Long.toHexString(System.currentTimeMillis()))
.build();
*/
return chain.proceed(newRequest);
}
};
可实现需求的方案
方案一: 在具体的请求每次动态添加参数或者请求头(不推荐)
@POST("login")
Observable<LoginResponseEntity> loginCall(
@Header("timestamp") String timestamp);
或者
@POST("login")
Observable<LoginResponseEntity> loginCall(
@Field("timestamp") String timestamp);
这种方式每个请求都要手动设置,所以不推荐使用。
方案二: 修改 RxJavaCallAdapter、自定义Call.Factory、OkHttpClient 三者结合
既然上诉方案不行,为什么我们不能换个角度去思考了,从Retrofit的源码入手,一个好的开源框架扩展性必定是很强的。首先来看下为什么要自定义Call.Factory,我们一起来看下Retrofit的源码都是怎么执行的吧。
/**
* Create the {@link Retrofit} instance using the configured values.
* <p>
* Note: If neither {@link #client} nor {@link #callFactory} is called a default {@link
* OkHttpClient} will be created and used.
*/
public Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
//这里去Builder获取Call.Factory并判空
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
// Make a defensive copy of the adapters and add the default Call adapter.
List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
callAdapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
// Make a defensive copy of the converters.
List<Converter.Factory> converterFactories =
new ArrayList<>(1 + this.converterFactories.size());
// Add the built-in converter factory first. This prevents overriding its behavior but also
// ensures correct behavior when using converters that consume all types.
converterFactories.add(new BuiltInConverters());
converterFactories.addAll(this.converterFactories);
return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories),
unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly);
}
通过查看build方法中知道,当Call.Factory对象为空时会创建一个OKHttpClient实例。为什么要创建一个OkHttpClient实例,点击去你会发现OKHttpClient正是Call.Factory的实现类,然后我们看下Call.Factory这个接口吧。
interface Factory {
Call newCall(Request request);
}
没错只有一个方法,查看实现类只有OKHttpClient,看看实现类OKHttpClient的重写方法newCall(Request request)具体做了什么操作吧
/**
* Prepares the {@code request} to be executed at some point in the future.
*/
@Override public Call newCall(Request request) {
return RealCall.newRealCall(this, request, false /* for web socket */);
}
看这个方法具体返回了什么点击RealCall这个类去查看一下,没错你会发现OkHttp的同步异步请求都在这里进行请求的。
@Override public Response execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
eventListener.callStart(this);
try {
client.dispatcher().executed(this);
Response result = getResponseWithInterceptorChain();
if (result == null) throw new IOException("Canceled");
return result;
} catch (IOException e) {
eventListener.callFailed(this, e);
throw e;
} finally {
client.dispatcher().finished(this);
}
}
在返回OkHttpClient中的newCall方法看下是谁调用了它
/** Builds an HTTP request from method arguments. */
okhttp3.Call toCall(@Nullable Object... args) throws IOException {
RequestBuilder requestBuilder = new RequestBuilder(httpMethod, baseUrl, relativeUrl, headers,
contentType, hasBody, isFormEncoded, isMultipart);
@SuppressWarnings("unchecked") // It is an error to invoke a method with the wrong arg types.
ParameterHandler<Object>[] handlers = (ParameterHandler<Object>[]) parameterHandlers;
int argumentCount = args != null ? args.length : 0;
if (argumentCount != handlers.length) {
throw new IllegalArgumentException("Argument count (" + argumentCount
+ ") doesn't match expected count (" + handlers.length + ")");
}
for (int p = 0; p < argumentCount; p++) {
handlers[p].apply(requestBuilder, args[p]);
}
return callFactory.newCall(requestBuilder.build());
}
会发现在ServiceMethod这个类中调用,我们知道Retrofit是采用动态代理的原理,源码太多这里就不做分析了,有兴趣的可以自己研究查看一下源码,这里就直接上解决方法其实很简单。
-
自定义Call.Factory,为什么要传入OkHttpClient,这样可以直接调用OkHttpClient的newCall(request)方法将重定向的请求创建成Call对象返回。
public class CallFactory implements Call.Factory { private OkHttpClient mOkHttpClient; public CallFactory(OkHttpClient okHttpClient) { mOkHttpClient = okHttpClient; } @Override public Call newCall(Request request) { Request newRequest; //创建新的URL HttpUrl modifiedUrl = request.url().newBuilder() .addQueryParameter(INetParameterConstant.NET_TARGET, Long.toHexString(System.currentTimeMillis())) .build(); //请求重定向 newRequest = request.newBuilder().url(modifiedUrl).build(); /* //以头文件的方式添加 Request newRequest = request.newBuilder() .addHeader("timestamp", Long.toHexString(System.currentTimeMillis())) .build(); */ return mOkHttpClient.newCall(newRequest); } }
然后在Retrofit初始化的时候传入CallFactory
mRetrofit = new Retrofit.Builder().baseUrl(BASE_URL)
.client(client)
.callFactory(new CallFactory(client)) //自定义CallFactory
.addConverterFactory(ResponseConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //自定义RxJava2CallAdapter
.build();
- 捕获异常请求的Call,需要更改RxJava2CallAdapter的源码。没关系把库下载下来,修改完成后,打包成jar或者arr包直接使用,也可直接拷贝到本地。直接找到CallEnqueueObservable和 CallExecuteObservable这两个类,下面就以CallExecuteObservable为例:找到subscribeActual(Observer<? super Response<T>> observer)这个方法(CallEnqueueObservable是onResponse(Call<T> call, Response<T> response)这个方法)找到捕获异常的代码,然后自定义一个异常将Call存放进去。
protected void subscribeActual(Observer<? super Response<T>>
observer) { // Since Call is a one-shot type, clone it for each new
observer. Call<T> call = originalCall.clone(); CallDisposable
disposable = new CallDisposable(call);
observer.onSubscribe(disposable); if (disposable.isDisposed()) {
return; }
boolean terminated = false;
try {
Response<T> response = call.execute();
if (!disposable.isDisposed()) {
observer.onNext(response);
}
if (!disposable.isDisposed()) {
terminated = true;
observer.onComplete();
}
} catch (Throwable t) {
//处理请求,自定义返回携带请求异常类,一定要把捕获的异常放进去,非常重要
//自定义的异常其实是一个壳
NetThrowable netThrowable = new NetThrowable(t, call.request().url());
Exceptions.throwIfFatal(netThrowable);
if (terminated) {
RxJavaPlugins.onError(netThrowable);
} else if (!disposable.isDisposed()) {
try {
observer.onError(netThrowable);
} catch (Throwable inner) {
Exceptions.throwIfFatal(netThrowable);
RxJavaPlugins.onError(new CompositeException(netThrowable, inner));
}
}
}
}
异常类
public class NetThrowable extends Throwable {
private HttpUrl url;
private Throwable realThrowable; //真实的异常
public HttpUrl getUrl() {
return url;
}
public void setUrl(HttpUrl url) {
this.url = url;
}
public Throwable getRealThrowable() {
return realThrowable;
}
public void setRealThrowable(Throwable realThrowable) {
this.realThrowable = realThrowable;
}
public NetThrowable(Throwable realThrowable, HttpUrl url) {
this.realThrowable = realThrowable;
this.url = url;
}
}
-
在DisposableObserver或者Observer的OnError中取出想要的值
public void onError(@NonNull Throwable t) { if (t instanceof NetThrowable) { NetThrowable netThrowable = (NetThrowable) t; Throwable e = netThrowable.getRealThrowable(); HttpUrl url = netThrowable.getUrl(); String timestamp = url.queryParameter("timestamp"); } }
好了本期分享就到这了,第一次写博客,写的不好之处大家见谅