[Android] Using Retrofit for network requests

The following is a Kotlin code example that uses Retrofit to send a POST request to obtain a paginated city list.

1. Add the dependencies of Retrofit and Gson to your build.gradle file

dependencies {
	......
    implementation("com.squareup.retrofit2:retrofit:2.9.0")
    implementation("com.squareup.retrofit2:converter-gson:2.9.0")
}

 

2. Apply for network permissions

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
      
    <uses-permission android:name="android.permission.INTERNET" />
    ......

</manifest>

 

3. Define data classes

data class CityResponse(
    val code: String,
    val message: String,
    val data: CityDataInfo
)

data class  CityDataInfo(
    val page: Int,
    var pageSize: Int,
    var totalPages: Int,
    var totalItems: Int,
    val data: List<CityModel>
)

data class CityModel(
    val id: Int,
    val name: String,
    val code: String
)

data class PageRequest(
    val page: Int,
    val pageSize: Int
)

The data format is as follows:

 

4. Define a Retrofit interface

import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST

interface ApiService {
    @POST("api/cityList.php")
    fun getCities(@Body request: PageRequest): Call<CityResponse>
}

In this interface, the @POST annotation indicates that this is a POST request, "api/cityList.php" is your API endpoint, getCities is your request method, which accepts a PageRequest object as the request body and returns an object.

 

5. Create a Retrofit instance to send POST requests

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class HomeFragment: Fragment() {

    private var dataArr: List<CityModel> = listOf()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        requestCityList()
    }

    private fun requestCityList() {
        val retrofit = Retrofit.Builder()
            .baseUrl("https://www.lnktools.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val service = retrofit.create(ApiService::class.java)
        val call = service.getCities(PageRequest(1, 20))

        call.enqueue(object : Callback<CityResponse> {
            override fun onResponse(call: Call<CityResponse>, response: Response<CityResponse>) {
                if (response.isSuccessful) {
                    val res = response.body()
                    var info = res?.data
                    var list = info?.data
                    dataArr += list ?: listOf()
                    // 处理响应
                    println("dataArr count = ${dataArr.count()}")
                } else {
                    // 处理错误
                }
            }

            override fun onFailure(call: Call<CityResponse>, t: Throwable) {
                // 处理失败
            }
        })
    }

}

This code first creates a Retrofit instance and configures the base URL and Gson converter. Then, we use the retrofit.create method to create an instance of ApiService. Finally, we call the getCities method to send the POST request and the enqueue method to send the request asynchronously. In the onResponse method of Callback, we can handle the server's response, and in the onFailure method, we can handle the request failure.

6. Network security configuration

Normally, it is no problem to complete the network request according to the above operations. However, when setting up a proxy packet capture on the mobile phone, the network request may still fail. In this case, it can be handled as follows.

Go to res -> xml to create a network-security-config.xml file with the following configuration.

<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
            <certificates src="user" />
        </trust-anchors>
    </base-config>
</network-security-config>

Then, go to the manifest file to configure networkSecurityConfig for the application.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

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

    <application android:networkSecurityConfig="@xml/network_security_config" >
 
    </application>

</manifest>

Note: Allow plaintext traffic in development settings cleartextTrafficPermitted="true"to facilitate packet capture. However, when publishing an application, in order to improve the security of the application, it is usually recommended to disable plaintext traffic, which is to  cleartextTrafficPermitted be set to  false. This ensures that applications can only communicate with the server through encrypted HTTPS connections, preventing sensitive data from being stolen or tampered with.

Guess you like

Origin blog.csdn.net/u012881779/article/details/134549716