Diary of Duc

Android – Retrofit

2019-03-13

Giới thiệu

Retrofit là thư viện được viết bằng Java, mục đích để dễ dàng gửi Request HTTP, HTTPS lên Server.

Hỗ trợ phương thức POST, GET, PUT, DELETE.

Hỗ trợ ánh xạ Json sang Gson.

* Gson: Ánh xạ Json Object sang Java/Kotlin Object.

Sử dụng

Import thư viện cần thiết:
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'

Chúng ta sẽ xây dựng 1 ứng dụng tìm kiếm thành phố trên thế giới đơn giản đơn giản với API có sẵn

API

API: https://location-query.herokuapp.com/location?key_word=<key_word>

* key_word: Là từ khóa cần tìm kiếm

Ví dụ tìm kiếm London:
https://location-query.herokuapp.com/location?key_word=london

Response:

{
   "code":200,
   "key_word":"london",
   "result":[
      {
         "id":2643743,
         "name":"London",
         "country":"GB",
         "coord":{
            "lon":-0.12574,
            "lat":51.50853
         }
      },
      {
         "id":2648110,
         "name":"Greater London",
         "country":"GB",
         "coord":{
            "lon":-0.16667,
            "lat":51.5
         }
      },
      {
         "id":1006984,
         "name":"East London",
         "country":"ZA",
         "coord":{
            "lon":27.911619,
            "lat":-33.015289
         }
      },
      {
         "id":2643734,
         "name":"Londonderry County Borough",
         "country":"GB",
         "coord":{
            "lon":-7.30917,
            "lat":54.997211
         }
      },
      {
         "id":2643744,
         "name":"City of London",
         "country":"GB",
         "coord":{
            "lon":-0.08901,
            "lat":51.51334
         }
      },
      {
         "id":5056033,
         "name":"London",
         "country":"US",
         "coord":{
            "lon":-95.234978,
            "lat":40.445
         }
      },
      {
         "id":6058560,
         "name":"London",
         "country":"CA",
         "coord":{
            "lon":-81.23304,
            "lat":42.983391
         }
      },
      {
         "id":4839420,
         "name":"New London County",
         "country":"US",
         "coord":{
            "lon":-72.066193,
            "lat":41.483429
         }
      },
      {
         "id":7535661,
         "name":"London Borough of Harrow",
         "country":"GB",
         "coord":{
            "lon":-0.33333,
            "lat":51.566669
         }
      },
      {
         "id":6058563,
         "name":"Londonderry",
         "country":"CA",
         "coord":{
            "lon":-63.598701,
            "lat":45.483452
         }
      },
      {
         "id":3489741,
         "name":"Little London",
         "country":"JM",
         "coord":{
            "lon":-78.216408,
            "lat":18.248301
         }
      },
      {
         "id":2643741,
         "name":"City of London",
         "country":"GB",
         "coord":{
            "lon":-0.09184,
            "lat":51.512791
         }
      },
      {
         "id":4839416,
         "name":"New London",
         "country":"US",
         "coord":{
            "lon":-72.099518,
            "lat":41.355652
         }
      },
      {
         "id":1644003,
         "name":"Glondong",
         "country":"ID",
         "coord":{
            "lon":111.891602,
            "lat":-6.7924
         }
      },
      {
         "id":4030939,
         "name":"London Village",
         "country":"KI",
         "coord":{
            "lon":-157.475021,
            "lat":1.98487
         }
      },
      {
         "id":4119617,
         "name":"London",
         "country":"US",
         "coord":{
            "lon":-93.25296,
            "lat":35.328972
         }
      },
      {
         "id":4298960,
         "name":"London",
         "country":"US",
         "coord":{
            "lon":-84.08326,
            "lat":37.128979
         }
      },
      {
         "id":4361094,
         "name":"Londontowne",
         "country":"US",
         "coord":{
            "lon":-76.549408,
            "lat":38.933449
         }
      },
      {
         "id":4400423,
         "name":"New London",
         "country":"US",
         "coord":{
            "lon":-91.400978,
            "lat":39.58532
         }
      },
      {
         "id":4517009,
         "name":"London",
         "country":"US",
         "coord":{
            "lon":-83.44825,
            "lat":39.886452
         }
      },
      {
         "id":4868768,
         "name":"New London",
         "country":"US",
         "coord":{
            "lon":-91.399597,
            "lat":40.926979
         }
      },
      {
         "id":5039111,
         "name":"New London",
         "country":"US",
         "coord":{
            "lon":-94.944183,
            "lat":45.301079
         }
      },
      {
         "id":5088905,
         "name":"Londonderry",
         "country":"US",
         "coord":{
            "lon":-71.373947,
            "lat":42.865089
         }
      },
      {
         "id":5090189,
         "name":"New London",
         "country":"US",
         "coord":{
            "lon":-71.985077,
            "lat":43.41396
         }
      },
      {
         "id":5164352,
         "name":"New London",
         "country":"US",
         "coord":{
            "lon":-82.399887,
            "lat":41.085049
         }
      },
      {
         "id":5264455,
         "name":"New London",
         "country":"US",
         "coord":{
            "lon":-88.73983,
            "lat":44.392761
         }
      },
      {
         "id":5367815,
         "name":"London",
         "country":"US",
         "coord":{
            "lon":-119.443176,
            "lat":36.476059
         }
      }
   ]
}
Ánh xạ Json vào Object Kotlin

CityCollection.kt

1
2
3
class CityCollection (val id: Long, val name: String, val country: String, val coord: Coord){
inner class Coord(val lon: Double, val lat: Double)
}

ResponseCollection.kt

1
class ResponseCollection (val code: Int, val key_word: String, val result: ArrayList<CityCollection>)

Xây dựng Interface cho API

API.kt

1
2
3
4
interface API {
@GET("location")
fun requestCity(@Query("key_word") key_word: String): Call<ResponseCollection>
}
Khởi tạo Retrofit

RetrofitCommon.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
class RetrofitCommon {

companion object {
private val retrofitBuilder =
Retrofit.Builder()
.baseUrl(Url.domain)
.addConverterFactory(GsonConverterFactory.create())
.build()

val retrofit = retrofitBuilder.create(API::class.java)
}

}
Xây dựng Interface để cập nhật giao diện

OnResponse.kt

1
2
3
4
interface OnResponse {
fun onResponse(cityCollection: ArrayList<CityCollection>)
fun onFail(m: String)
}
Request tới API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class RequestCity(private val onResponse: OnResponse) {

private lateinit var request: Call<ResponseCollection>

fun request(key_word: String) {
request = RetrofitCommon.retrofit.requestCity(key_word)

request.enqueue(object : Callback<ResponseCollection> {
override fun onFailure(call: Call<ResponseCollection>, t: Throwable) {
if (!request.isCanceled)
onResponse.onFail(t.toString())
}

override fun onResponse(call: Call<ResponseCollection>, response: Response<ResponseCollection>) {
val body = response.body()
body?.let {
if (!request.isCanceled) {
if (it.code == 200)
onResponse.onResponse(it.result)
else
onResponse.onFail("Not Found")
}
}
}

})
}

fun cancel() {
request.cancel()
}
}

Tags: android

URL QR