技術學習記錄

[Android]使用Retrofit與API連線

Retrofit是一款專門用來處理網路請求的框架,由知名的OkHttp開發團隊Square所開發。

Retrofit遵循RESTful的設計風格,具有簡單、易上手的特性,同時也支援JSON、XML等資料格式序列化。

Retrofit的底層基於OkHttp,一般來說使用Retrofit內建的OkHttp Client即可。

但如果有特殊需求,比方說自訂Header欄位或是加入攔截器等,那麼也可以自訂一個OkHttp Client物件給Retrofit使用,彈性非常的大。

使用方式

1.在使用Retrofit之前,首先需要在Android Studio專案中加入Retrofit的依賴,如下:

// Retrofit 本體
compile 'com.squareup.retrofit2:retrofit:2.1.0'
// Retrofit Gson 轉換器
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

2.由於Retrofit需要internet權限才能使用,因此要在Android Manifest.xml中加入權限,如下:

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

3.建立資料模型,如下:

data class Student(
    val exams: ArrayList<Exam>,
    val id: Int,
    val name: String
)

data class Exam(
    val score: Int,
    val subjectName: String
)

4.建立ApiService Interface,如下:

interface ApiService {

    @GET("api_demo/students")
    fun getStudents(): Call<ArrayList<Student>>

    @GET("api_demo/students/{id}")
    fun getStudent(@Path("id") id: Int): Call<Student>

}

5.建立RetrofitClient,如下:

object RetrofitClient {

    private val retrofitClient: Retrofit.Builder by lazy {
        Retrofit.Builder()
            .baseUrl("https://my-json-server.typicode.com/ray650128")
            .addConverterFactory(GsonConverterFactory.create())
    }

    val api: ApiService
        get() = retrofitClient.build().create(ApiService::class.java)
}

6.呼叫RetrofitClient.api來請求網路上的資料:

class MainActivity : AppCompatActivity() {
    
    private val TAG = MainActivity::class.java.simpleName

    private var students = ArrayList<Student>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        getStudents()
    }

    fun getStudents() {
        val call = RetrofitClient.api.getStudents()
        call.enqueue(object : Callback<ArrayList<Student>> {
            override fun onResponse(call: Call<ArrayList<Student>>, response: Response<ArrayList<Student>>) {
                if (response.isSuccessful) {
                    students  = response.body()
                    Log.e(TAG, "${students.size}")
                }
            }

            override fun onFailure(call: Call<ArrayList<Student>>, t: Throwable) {
                Log.e(TAG, "error: ${t.message}")
            }
        })
    }
}

以上就是Retrofit的簡單示範。

雖然上面只展示了HTTP中的GET請求方法,但只要瞭解了如何實作後。

其他諸如POST、PUT、PATCH、DELETE等請求,其實是大同小異的。

以下附上幾篇文章供參考:

深入浅出 Retrofit,这么牛逼的框架你们还不来看看?

Retrofit · Android third-party 使用心得

iT邦幫忙Android初學筆記系列 第 24 篇 Day 24 – 使用Retrofit與API連線

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *