前面介绍了request篇的处理,这里我们进入最后一篇章response篇,response这里会介绍retrofit对response的处理,在加上retrofit内部做的解耦操作(即需要我们出入的好比RxJavaCallAdapter和GsonConverterFactory)这块的处理
toResponse
该方法也是在retrofit的ServiceMethod,其用意就是帮助我们建造一个我们想要的返回体
/** Builds a method return value from an HTTP response body. */ R toResponse(ResponseBody body) throws IOException { return responseConverter.convert(body); }
提起Response就又得提到我们之前传递的Converter
Converter
在接口Converter中,retrofit声明了converter方法和一个工厂类,提供给我们使用
这个factory呢,对json处理这块做了解耦,以便于我们使用自己喜欢的json处理工具,开篇我举例的GsonConverterFactory就是其实现之一,也就是说,我们只要实现这个factory,我们就可以使用我们想使用的json处理工具就行
factory中声明了三个方法
abstract class Factory {
/**
* 响应转换器
*/
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
return null;
}
/**
* 请求转换器
*/
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return null;
}
/**
* string转换器
*/
public Converter<?, String> stringConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
return null;
}
}
我们以GsonConverterFactory为例解析:
其实现均用了GsonRequestBodyConverter,在GsonRequestBodyConverter中
就是帮我们做一个json的处理
@Override public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
JsonWriter jsonWriter = gson.newJsonWriter(writer);
adapter.write(jsonWriter, value);
jsonWriter.close();
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
到这里retrofit的response外部补充部分就完成了,接下来我们看看它的调用链
Call发起与响应
上一文中我们分析了ServiceMethod的部分,对与retrofit的核心方法就剩下余下的两行:
我们已经ServiceMethod中存放着我们接口的所有信息(地址/参数),接下来retrofit通过OkhttpCall整合我们的参数返给我们请求
okhttpCall
okhttpCall是基于okhttp3的call方法扩展的,这也是为什么说retrofit是基于okhttp开发的说法由来。
okhttpCall内部方法很多,这里仅以execute()方法详细赘述其流转
@Override public Response<T> execute() throws IOException {
okhttp3.Call call;
synchronized (this) {
...省略部分代码...
call = rawCall;
if (call == null) {
try {
/*
* 通过okhttp创建一个请求
*/
call = rawCall = createRawCall();
} catch (IOException | RuntimeException e) {
creationFailure = e;
throw e;
}
}
}
if (canceled) {
call.cancel();
}
/**
* 通过call.execute方法发起请求,并处理其返回结果
*/
return parseResponse(call.execute());
}
private okhttp3.Call createRawCall() throws IOException {
/**
* 通过serviceMethod的toRequest方法对请求链接处理
*/
Request request = serviceMethod.toRequest(args);
okhttp3.Call call = serviceMethod.callFactory.newCall(request);
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
/**
* 创建一个响应体
*/
ResponseBody rawBody = rawResponse.body();
// Remove the body's source (the only stateful object) so we can pass the response along.
rawResponse = rawResponse.newBuilder()
.body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength()))
.build();
...省略部分代码
ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
try {
/**
* 通过serviceMethod的toResponse方法,通过我们coverter处理我们想 * 要的结果
*/
T body = serviceMethod.toResponse(catchingBody);
return Response.success(body, rawResponse);
} catch (RuntimeException e) {
catchingBody.throwIfCaught();
throw e;
}
}
到这里可能有人有疑问到底在哪触发,retrofit这里也有个不错的设计,在retrofit核心方法上有这么一句:
serviceMethod.callAdapter.adapt(okHttpCall);
其通过callAdapter的adapt将执行权返回给我们,由我们触发
callAdapter这里以内置的DefaultCallAdapterFactory举例
看到了么?其直接将call对象返给我们,这也是我们直接通过call.execute()的原因
###结语
整个retrofit到这里就分析完毕,整个过程从request的解析处理到response的处理,完完整整的一个执行顺序,能看出其解耦操作值得大力学习