Retrofit是基于Okhttp封装的一套网络请求库
认识Retrofit
Retrofit注解
注解: Java注解(Annotation),是JDK5.0引入的一种注释机制同时也增加了对元数据的支持,这些注释在编译,类加载,运行时被读取,进行相应的处理。
请求注解 | 使用详情 |
---|---|
GET请求(返回页面信息主体) | @Get(“Url”) |
POST请求(提交数据进行操作) | @POST(“Url”) |
DELETE请求(删除request-URL所标识的资源) | @DELETE(“Url”) |
PUT请求(向服务端上传资源) | @PUT(“Url”) |
HEAD请求(与GET差不多,但是是获取报头) | @HEAD(“Url”) |
HTTP请求可以通过注解转换成其他的请求 | @HTTP(method = “GET”, path=“Url”) |
OPTIONS请求(发送测试服务器请求) | @OPTIONS(“Url”) |
PATCH请求(PUT相近但是资源不存在会新建资源文件) | @POST(“Url”) |
Retrofit通过这些注解封装请求体,后续需要用到的会在代码中解释
实战阶段
新建项目
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KpjqzcBT-1652841656500)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/2a8eff84387b40ad9ec7240ba7c258eb~tplv-k3u1fbpfcp-watermark.image?)]
将一些后续需要使用的进行导入(Okio,OKHTTP,Retrofit,coil,gson)
//build.gradle(Module:XXX.App)
//dependences中添加
//okhttp io流处理
implementation "com.squareup.okio:okio:2.3.0"
//协程依赖
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0-RC-native-mt'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0-RC-native-mt'
//KTX
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
//coil
implementation("io.coil-kt:coil:1.2.1")
//gson
implementation 'com.google.code.gson:gson:2.8.6'
//okhttp
implementation("com.squareup.okhttp3:okhttp:4.9.0")
//retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//开启ViewBining,android标签下
buildFeatures{
viewBinding true
}
当然别忘了在AndroidMainifest
网络限权以及在applicatioan
标签内添加允许明文流量的请求
<uses-permission android:name="android.permission.INTERNET"/>
<application
...
android:usesCleartextTraffic="true"
使用接口
偷偷使用SpringBoot写一个GET请求接口,一个POST请求接口
@GetMapping("/test")
public String getText(String name){
return "Hello "+name;
}
@PostMapping("/queryByName")
public String readFile(@RequestBody String fileName){
return "Hello "+fileName;
}
创建接口请求类
interface ApiService{
@GET("/test?name=Retrofit")
suspend fun test():String
@FormUrlEncoded
@POST("/queryByName")
suspend fun queryByName(@Field("fileName") name:String):String
}
创建Retrofit辅助类,添加BaseUrl以及数据解析器
object RetrofitUtil {
private const val BASE_URL = "http://192.168.0.106:8080"
private val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
//Scalar用于解析String数据
.addConverterFactory(ScalarsConverterFactory.create())
.build()
fun <T> create(service: Class<T>):T = retrofit.create(service)
}
Converter中支持了许多数据解析器,需要使用就在项目中添加依赖
com.squareup.retrofit2:converter-${XXXX}:version
Gson、Jackson、Simple XML、Protobuf、Moshi、Wire、Scalars
创建MainViewModel类,进行数据的请求处理
class MianViewModel : ViewModel() {
var mainviewLiveData = MutableLiveData<String>()
private val api = RetrofitUtil.create(ApiService::class.java)
fun getQueryByName(){
viewModelScope.launch {
flow {
emit(api.queryByName("Retrofit"))
}.collect {
mainviewLiveData.postValue(it)
}
}
}
fun getTest(){
viewModelScope.launch {
flow {
emit(api.test())
}.collect {
mainviewLiveData.postValue(it)
}
}
}
}
测试
最后在activity_main布局中创建一个按钮(btnClick),一个文本(textTitle)用于测试
private val mainViewModel by viewModels<MianViewModel>()
override fun init() {
b.btnClick.setOnClickListener {
mainViewModel.getQueryByName()
}
mainViewModel.mainviewLiveData.observe(this){
b.textTitle.setText(it)
}
}
可以观察到GET请求是可以请求到的
POST请求也成功获取
如果你也是本地写的接口测试数据,出现如下报错,可以将localhost换成本机IP地址
Retrofit的练习就此结束,多种请求的方式,使用的注解与方法也不同
Retrofit Api
Field(表单编码请求的命名对)、FieldMap(表单编码请求的命名键/值对)、FormUelEncoded(表示请求将使用表单URL编码)、Header(将标头替换为其目标的值。 标头参数可能会从请求中省略它们。)、Headers(添加Map或中指定的标头。)、Multipart(表示请求正文是多部分的。)、Part(表示多部分请求的单个部分。)、Path(URL 路径段中的命名替换)、Query(附加到 URL 的查询参数。)、Streaming(按原样对待返回方法上的响应正文)、Tag(使用类型作为键将参数实例添加为请求标记。)、Url(针对基本 URL解析的 URL。)
只是一篇简单的学习日记有不足见谅