Into the Retrofit network request library - Kotlin version

Retrofit is a set of network request library based on Okhttp package

Meet Retrofit

Retrofit annotations

注解: Java注解(Annotation),是JDK5.0引入的一种注释机制同时也增加了对元数据的支持,这些注释在编译,类加载,运行时被读取,进行相应的处理。

request for comment Usage details
GET request (returns the body of the page information) @Get("Url")
POST request (submit data for operation) @POST("Url")
DELETE request (delete the resource identified by request-URL) @DELETE("Url")
PUT request (upload resources to the server) @PUT("Url")
HEAD request (similar to GET, but get headers) @HEAD("Url")
HTTP requests can be converted into other requests through annotations @HTTP(method = "GET", path="Url")
OPTIONS request (send test server request) @OPTIONS("Url")
PATCH request (PUT is similar but the resource does not exist, a new resource file will be created) @POST("Url")

Retrofit encapsulates the request body through these annotations, and the subsequent needs will be explained in the code

actual combat stage

New Project

image.png

Import some subsequent use (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
}

复制代码

Of course, don't forget to add the request to allow clear text traffic in the AndroidMainifestnetwork permissions and in the applicatioanlabel

<uses-permission android:name="android.permission.INTERNET"/>

<application
    ...
    android:usesCleartextTraffic="true"

复制代码

use interface

Secretly use SpringBoot to write a GET request interface and a POST request interface

@GetMapping("/test")
public String getText(String name){
    return "Hello "+name;
}
复制代码

image.png

@PostMapping("/queryByName")
public String readFile(@RequestBody String fileName){
    return "Hello "+fileName;
}
复制代码

image.png

Create interface request class

interface ApiService{

    @GET("/test?name=Retrofit")
    suspend fun test():String

    @FormUrlEncoded
    @POST("/queryByName")
    suspend fun queryByName(@Field("fileName") name:String):String
}
复制代码

Create Retrofit helper class, add BaseUrl and data parser

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 supports many data parsers, add dependencies to the project if you need to use them

com.squareup.retrofit2:converter-${XXXX}:version
Gson、Jackson、Simple XML、Protobuf、Moshi、Wire、Scalars
复制代码

Create the MainViewModel class for data request processing

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)
            }
        }
    }
}
复制代码

test

Finally create a button (btnClick) in the activity_main layout and a text (textTitle) for testing

private val mainViewModel by viewModels<MianViewModel>()
override fun init() {
    b.btnClick.setOnClickListener {
        mainViewModel.getQueryByName()
    }
    mainViewModel.mainviewLiveData.observe(this){
        b.textTitle.setText(it)
    }
}
复制代码

It can be observed that GET requests can be requested

image.png

POST request is also successfully fetched

image.png

If you also write the interface test data locally, and the following error occurs, you can replace localhost with the local IP address

image.png

Retrofit的练习就此结束,多种请求的方式,使用的注解与方法也不同

Retrofit Api

Field(表单编码请求的命名对)、FieldMap(表单编码请求的命名键/值对)、FormUelEncoded(表示请求将使用表单URL编码)、Header(将标头替换为其目标的值。 标头参数可能会从请求中省略它们。)、Headers(添加Map或中指定的标头。)、Multipart(表示请求正文是多部分的。)、Part(表示多部分请求的单个部分。)、Path(URL 路径段中的命名替换)、Query(附加到 URL 的查询参数。)、Streaming(按原样对待返回方法上的响应正文)、Tag(使用类型作为键将参数实例添加为请求标记。)、Url(针对基本 URL解析的 URL。)

只是一篇简单的学习日记有不足见谅

Guess you like

Origin juejin.im/post/7097477184184385567