Hanbit the Developer
[Kotlin] Send Get-Request to api server And Get Response Using retrofit2 본문
Android
[Kotlin] Send Get-Request to api server And Get Response Using retrofit2
hanbikan 2021. 5. 28. 23:240. build.gradle
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
저장 후 'Sync Project With Gradle Files'는 필수이다.
1. Interface 및 데이터 형식 지정
MyApi.kt
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Query
interface MyApi {
@GET("ex/api.json")
fun getSearchKeyword(
@Header("h1") h1: String,
@Query("q1") q1: String,
@Query("q2") q2: String
): Call<Documents>
}
// 지정된 데이터셋
data class Documents(
var documents: List<Place>
)
data class Place(
var id: String
)
2. retrofit2
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
// ... In some class
private fun sendGetRequest(){
// Retrofit 구성
val retrofit = Retrofit.Builder()
.baseUrl("https://ex.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val api = retrofit.create(MyApi::class.java)
// GET 요청
try{
val call = api.getSearchKeyword("h1", "q1", "q2")
call.enqueue(object: Callback<Documents> {
override fun onResponse(
call: Call<Documents>,
response: Response<Documents>
) {
Log.i("성공", response.body().toString())
}
override fun onFailure(call: Call<Documents>, t: Throwable) {
Log.i("MainActivity", "Failed To Get Request: ${t.message}")
}
})
}catch(e: Exception){
Log.e("MainActivity", e.stackTrace.toString())
}
}
'Android' 카테고리의 다른 글
[kakaomap] 현재 위치 마커 커스텀 이미지로 변경하기 (0) | 2021.07.09 |
---|---|
[Kotlin] "전화하기" 기능 구현(4줄) (0) | 2021.07.02 |
Check If Permissions is granted or denied And Request Permissions in Android (0) | 2021.05.20 |
MapViewLocationManager: init failed 오류에 대한 해결책 두 가지 (0) | 2021.05.17 |
[build.gradle] I can't found libraries/modules after implements (0) | 2021.03.05 |