publicRetrofitbuild(){//1.必须指定baseUrlif(baseUrl ==null){thrownewIllegalStateException("Base URL required.");}//2.callFactory默认为this.callFactroyokhttp3.Call.Factory callFactory =this.callFactory;if(callFactory ==null){//3.
callFactory =newOkHttpClient();}//4.callbackExecutor用来回调传递给UI线程Executor callbackExecutor =this.callbackExecutor;if(callbackExecutor ==null){
callbackExecutor = platform.defaultCallbackExecutor();}//5.CallAdapterFactories主要用来存储对Call进行转化的对象// Make a defensive copy of the adapters and add the default Call adapter.List<CallAdapter.Factory> callAdapterFactories =newArrayList<>(this.callAdapterFactories);
callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));// 6.converterFactories主要用来存储转化数据对象List<Converter.Factory> converterFactories =newArrayList<>(1+this.converterFactories.size()+ platform.defaultConverterFactoriesSize());// 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(newBuiltInConverters());
converterFactories.addAll(this.converterFactories);
converterFactories.addAll(platform.defaultConverterFactories());returnnewRetrofit(callFactory, baseUrl,unmodifiableList(converterFactories),unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly);}
public<T>Tcreate(finalClass<T> service){validateServiceInterface(service);//newProxyInstance是个方法,内部有三个参数return(T)Proxy.newProxyInstance(service.getClassLoader(),newClass<?>[]{ service },newInvocationHandler(){privatefinalPlatform platform =Platform.get();privatefinalObject[] emptyArgs =newObject[0];//当我们调用IpService的getIpMsg方法时,最终会调用InvocationHandler的invoke方法@Overridepublic@NullableObjectinvoke(Object proxy,Method method,@NullableObject[] args)throwsThrowable{// If the method is a method from Object then defer to normal invocation.if(method.getDeclaringClass()==Object.class){return method.invoke(this, args);}if(platform.isDefaultMethod(method)){return platform.invokeDefaultMethod(method, service, proxy, args);}returnloadServiceMethod(method).invoke(args !=null? args : emptyArgs);}});}
static<T>ServiceMethod<T>parseAnnotations(Retrofit retrofit,Method method){RequestFactory requestFactory =RequestFactory.parseAnnotations(retrofit, method);Type returnType = method.getGenericReturnType();if(Utils.hasUnresolvableType(returnType)){throwmethodError(method,"Method return type must not include a type variable or wildcard: %s", returnType);}if(returnType ==void.class){throwmethodError(method,"Service methods cannot return void.");}returnHttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);}
static<ResponseT,ReturnT>HttpServiceMethod<ResponseT,ReturnT>parseAnnotations(Retrofit retrofit,Method method,RequestFactory requestFactory){boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;boolean continuationWantsResponse =false;boolean continuationBodyNullable =false;Annotation[] annotations = method.getAnnotations();Type adapterType;if(isKotlinSuspendFunction){Type[] parameterTypes = method.getGenericParameterTypes();Type responseType =Utils.getParameterLowerBound(0,(ParameterizedType) parameterTypes[parameterTypes.length -1]);if(getRawType(responseType)==Response.class&& responseType instanceofParameterizedType){// Unwrap the actual body type from Response<T>.
responseType =Utils.getParameterUpperBound(0,(ParameterizedType) responseType);
continuationWantsResponse =true;}else{// TODO figure out if type is nullable or not// Metadata metadata = method.getDeclaringClass().getAnnotation(Metadata.class)// Find the entry for method// Determine if return type is nullable or not}
adapterType =newUtils.ParameterizedTypeImpl(null,Call.class, responseType);
annotations =SkipCallbackExecutorImpl.ensurePresent(annotations);}else{
adapterType = method.getGenericReturnType();}//1.调用了createCallAdapter方法CallAdapter<ResponseT,ReturnT> callAdapter =createCallAdapter(retrofit, method, adapterType, annotations);//2.返回数据的真实类型Type responseType = callAdapter.responseType();if(responseType ==okhttp3.Response.class){throwmethodError(method,"'"+getRawType(responseType).getName()+"' is not a valid response body type. Did you mean ResponseBody?");}if(responseType ==Response.class){throwmethodError(method,"Response must include generic type (e.g., Response<String>)");}// TODO support Unit for Kotlin?if(requestFactory.httpMethod.equals("HEAD")&&!Void.class.equals(responseType)){throwmethodError(method,"HEAD method must use Void as response type.");}//3.调用createResponseConverter方法来遍历converterFactories列表中存储的Converter.Factory//并返回一个合适的Converter用来转换对象Converter<ResponseBody,ResponseT> responseConverter =createResponseConverter(retrofit, method, responseType);okhttp3.Call.Factory callFactory = retrofit.callFactory;if(!isKotlinSuspendFunction){//CallAdapted类继承自HttpServiceMethod类,并实现了adapt抽象方法//HttpServiceMethod继承自ServiceMethod//Retrofit的create方法中的loadServiceMethod方法实际上返回HttpServiceMethod对象。returnnewCallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);}elseif(continuationWantsResponse){//noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.return(HttpServiceMethod<ResponseT,ReturnT>)newSuspendForResponse<>(requestFactory,
callFactory, responseConverter,(CallAdapter<ResponseT,Call<ResponseT>>) callAdapter);}else{//noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.return(HttpServiceMethod<ResponseT,ReturnT>)newSuspendForBody<>(requestFactory,
callFactory, responseConverter,(CallAdapter<ResponseT,Call<ResponseT>>) callAdapter,
continuationBodyNullable);}}
Response<T>parseResponse(okhttp3.Response rawResponse)throwsIOException{ResponseBody rawBody = rawResponse.body();// 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();int code = rawResponse.code();if(code <200|| code >=300){try{// Buffer the entire body to avoid future I/O.ResponseBody bufferedBody =Utils.buffer(rawBody);returnResponse.error(bufferedBody, rawResponse);}finally{
rawBody.close();}}if(code ==204|| code ==205){
rawBody.close();returnResponse.success(null, rawResponse);}ExceptionCatchingResponseBody catchingBody =newExceptionCatchingResponseBody(rawBody);try{T body = responseConverter.convert(catchingBody);returnResponse.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;}}