Retrofit官网
GitHub上的Retrofit
使用Retrofit进行网络请求的主要步骤
- 创建一个接口
用于描述HTTP请求。接口里的方法使用注解来标记请求方式、API路径、请求参数等信息。- 使用Retrofit.Builder().build();配置和创建一个Retrofit实例;
- 调用retrofit.create()方法获取请求接口实例;
- 由请求接口实例获取到Call对象;
- 进行网络请求(同步/异步)
接口 APIService.java代码
package example.demo.testandroidx.http;import example.demo.testandroidx.base.BaseResponse;
import example.demo.testandroidx.entity.LoginRequset;
import io.reactivex.rxjava3.core.Observable;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;public interface APIService {/*登录接口用POST方式发起请求请求参数用Body对象传入*/@POST(HttpsUrl.LOGIN)Observable<BaseResponse<String>> login(@Body LoginRequset loginRequset);/*获取文章信息接口用GET方式发起请求*/@GET("wxarticle/chapters/json")Observable<ResponseBody> getContent();
}
封装RetrofitHelper.java代码
public class RetrofitHelper {public static volatile APIService sAPIService;private static final int DEFAULT_TIMEOUT = 20; // 20 SECONDSprivate static final int DEFAULT_READ_TIMEOUT = 30; // 20 SECONDSpublic static APIService createAPIService() {if (sAPIService == null) {synchronized (RetrofitHelper.class) {Retrofit retrofit = new Retrofit.Builder().baseUrl(HttpsUrl.BASE_URL).client(getOkHttpClient()).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJava3CallAdapterFactory.create()).build();/*https://blog.csdn.net/hu582205/article/details/108800768Unable to create call adapter for io.reactivex.rxjava3.core.Observable*/sAPIService = retrofit.create(APIService.class);}}return sAPIService;}public static OkHttpClient getOkHttpClient() {OkHttpClient.Builder builder = new OkHttpClient.Builder();builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS).readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS).writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS).cookieJar(new CustomCookieJar()).addInterceptor(new TokenInterceptor()).addInterceptor(new PublicParamInterceptor());if (BuildConfig.DEBUG) {HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);builder.addInterceptor(httpLoggingInterceptor);}return builder.build();}
}
Retrofit.java里的create 方法
通过调用retrofit.create(APIService.class);获取请求接口APIService的实例
Retrofit.java里的loadServiceMethod 方法
ServiceMethod.java代码
ServiceMethod类负责解析接口方法的注解信息,并构建请求对象
RequestFactory.java里的parseAnnotations方法
RequestFactory.java里Builder内部类里的parseMethodAnnotation方法
HttpServiceMethod.java里的parseAnnotations方法
parseAnnotations()
作用:解析注解信息,并创建CallAdapter和Converter,最终返回CallAdapted类型的ServiceMethod实例。