Builder(Platform platform) { this.platform = platform; // Add the built-in converter factory first. This prevents overriding its behavior but also // ensures correct behavior when using converters that consume all types. // 默认内置的数据转换器 BuiltInConverters converterFactories.add(newBuiltInConverters()); }
public Retrofit build() { if (baseUrl == null) { thrownewIllegalStateException("Base URL required."); } // 默认为 OkHttpClient okhttp3.Call.FactorycallFactory=this.callFactory; if (callFactory == null) { callFactory = newOkHttpClient(); } // Android 平台下默认为 MainThreadExecutor ExecutorcallbackExecutor=this.callbackExecutor; if (callbackExecutor == null) { callbackExecutor = platform.defaultCallbackExecutor(); } // // Make a defensive copy of the adapters and add the default Call adapter. List<CallAdapter.Factory> adapterFactories = newArrayList<>(this.adapterFactories); // 添加 ExecutorCallAdapterFactory adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
// Make a defensive copy of the converters. 默认有 BuiltInConverters List<Converter.Factory> converterFactories = newArrayList<>(this.converterFactories);
if (httpMethod == null) { throw methodError("HTTP method annotation is required (e.g., @GET, @POST, etc.)."); }
// 若无 body 则不能有 isMultipart 和 isFormEncoded if (!hasBody) { if (isMultipart) { throw methodError( "Multipart can only be specified on HTTP methods with request body (e.g., @POST)."); } if (isFormEncoded) { throw methodError("FormUrlEncoded can only be specified on HTTP methods with " + "request body (e.g., @POST)."); } }
// 下面的代码主要用来解析接口方法参数中的注解,比如 @Path @Query @QueryMap @Field 等等 // 相应的,每个方法的参数都创建了一个 ParameterHandler<?> 对象 intparameterCount= parameterAnnotationsArray.length; parameterHandlers = newParameterHandler<?>[parameterCount]; for (intp=0; p < parameterCount; p++) { TypeparameterType= parameterTypes[p]; if (Utils.hasUnresolvableType(parameterType)) { throw parameterError(p, "Parameter type must not include a type variable or wildcard: %s", parameterType); }
Annotation[] parameterAnnotations = parameterAnnotationsArray[p]; if (parameterAnnotations == null) { throw parameterError(p, "No Retrofit annotation found."); }
// 检查构造出的请求有没有不对的地方? if (relativeUrl == null && !gotUrl) { throw methodError("Missing either @%s URL or @Url parameter.", httpMethod); } if (!isFormEncoded && !isMultipart && !hasBody && gotBody) { throw methodError("Non-body HTTP method cannot contain @Body."); } if (isFormEncoded && !gotField) { throw methodError("Form-encoded method must contain at least one @Field."); } if (isMultipart && !gotPart) { throw methodError("Multipart method must contain at least one @Part."); }
returnnewServiceMethod<>(this); }
在 build() 中代码挺长的,总结起来就一句话:就是将 API 接口中的方法进行解析,构造成 ServiceMethod ,交给下面的 OkHttpCall 使用。
// Remove the body's source (the only stateful object) so we can pass the response along. rawResponse = rawResponse.newBuilder() .body(newNoContentResponseBody(rawBody.contentType(), rawBody.contentLength())) .build(); // 如果返回的响应码不是成功的话,返回错误 Response intcode= rawResponse.code(); if (code < 200 || code >= 300) { try { // Buffer the entire body to avoid future I/O. ResponseBodybufferedBody= Utils.buffer(rawBody); return Response.error(bufferedBody, rawResponse); } finally { rawBody.close(); } } // 如果返回的响应码是204或者205,返回没有 body 的成功 Response if (code == 204 || code == 205) { return Response.success(null, rawResponse); }
ExceptionCatchingRequestBodycatchingBody=newExceptionCatchingRequestBody(rawBody); try { // 将 body 转换为对应的泛型,然后返回成功 Response Tbody= serviceMethod.toResponse(catchingBody); return Response.success(body, rawResponse); } catch (RuntimeException e) { // If the underlying source threw an exception, propagate that rather than indicating it was // a runtime exception. catchingBody.throwIfCaught(); throw e; } }