一:认识Retrofit和okhttp3
Retrofit是由square 开发设计的 网络请求框架
官方网址:Retrofit
Okhttp 是由square 开发设计的 网络请求库,请求/响应API采用流畅的构建器和不变性设计。它同时支持同步阻塞调用和带有回调的异步调用
官方网址:Overview - OkHttp
这篇博客是网络请求的基础篇,使用Retrofit作为网络请求及响应的载体,了解Retrofit的注解,Okhttp的作用在于日志过滤,以及完善网络请求(比如超时处理,请求体处理等)
使用方法如下:
在app\build.gradle
1:依赖Maven库
dependencies {
//retrofit2 okhttp3
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
implementation "com.squareup.okhttp3:logging-interceptor:4.7.2"
}
2:jar包依赖
在官网下载
二:准备工作
免费的Json数据接口 :
1:构造Retrofit对象
//构造retrofit,返回请求接口
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(builder.build())
.build();
service = retrofit.create(BaseService.class);
2:添加okhttp日志过滤器
//构造okhttp3,日志过滤
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT);
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if(BuildConfig.DEBUG){
builder.addInterceptor(interceptor);

本文介绍了Retrofit和Okhttp在网络请求中的应用。Retrofit是一个用于创建网络请求的框架,而Okhttp是网络请求库,两者结合使用可以方便地处理同步和异步请求。文章详细讲解了如何配置依赖、构建Retrofit对象、添加Okhttp日志过滤器、构建Callback、理解各种注解以及发起请求的过程。此外,还提到了源码分析和最新的技术趋势,如Retrofit结合Okhttp、Moshi和Kotlin协程的使用。
最低0.47元/天 解锁文章
829

被折叠的 条评论
为什么被折叠?



