Retrofit网络请求框架

1,998 阅读2分钟

Retrofit简介:

安全的http客户端,针对于Android和java

特征:

基于Okhttp

RESTful api设计风格

通过注解配置请求(请求方法,请求参数,请求头等)

可以搭配多个Converter将参数解析&序列化

默认支持Gson,jackson

支持Rxjava

官方文档:square.github.io/retrofit/

GitHub地址: square.github.io/retrofit/

demo的版本是:2.8.1

implementation 'com.squareup.retrofit2:retrofit:2.8.1'

这个版本需要注意的是支持的最低Java和Android版本

java8+和Android api 21+

基本使用步骤:

第一步:将http API转换为接口

定义方法通过注释配置请求方法,请求参数等,返回Call

interface GitHubService {    
@GET("users/{user}/repos")    
fun listRepos(@Path("user") user: String): Call<List<RepositoryBean>> 
    
@GET("users/{user}/repos")    
fun jsonBeanListRepos(@Path("user") user: String): Call<List<RepositoryJsonBean>>
}

第二步:Retrofit生成上面的接口

val retrofit = Retrofit.Builder()    
.baseUrl("https://api.github.com/")
//添加gson解析器
.addConverterFactory(GsonConverterFactory.create())    
.build()

val gitHubService = retrofit.create(GitHubService::class.java)

这里添加gson解析器:

implementation 'com.squareup.retrofit2:converter-gson:2.8.1'

第三步:接口调用方法返回Call,再Call.enqueue()

每个Call对象都可以向远处Web服务器发生同步或异步请求

val callRepos = gitHubService.jsonBeanListRepos("smilekoko")

//发送网络请求(异步)
callRepos.enqueue(object :Callback<List<RepositoryJsonBean>>{
            override fun onFailure(call: Call<List<RepositoryJsonBean>>, t: Throwable) {
                TODO("Not yet implemented")
            }

            override fun onResponse(
                call: Call<List<RepositoryJsonBean>>,
                response: Response<List<RepositoryJsonBean>>
          		) {
                val repositoryList = response.body()
                if (repositoryList != null) {
                    for (item in repositoryList) {
                        Log.e("koko", item.fullName)
                    }
                }
            }
     })

// 发送网络请求(同步)
val Response: Response<List<RepositoryJsonBean>> = callRepos.execute()

这里具体怎么处理然后的参数Response,参考文档

square.github.io/retrofit/2.…

同步请求:在服务器没返回结果给客户端之前,我们要一直处于等待状态直至服务器将结果返回到客户端,我们才能执行下一步操作。

异步请求:并行处理,当我们向服务器发出一个请求时,在服务器没返回结果之前,我们还是可以执行其他操作

demo地址:
github.com/Smilekoko/A…