划水:Retrofit三步走:Response篇

前面介紹了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的處理,完完整整的一個執行順序,能看出其解耦操作值得大力學習

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章