次のサンプルの
「Retrofit を使用して Kotlin で HTTP リクエストを作成する」
と同じことを行いました。
Kotlin で HTTP リクエストを作成する
サーバーは、こちらと同じ設定とします。
IntelliJ: Java 標準ライブラリーで HTTP リクエスト
環境
build.gradele.kts
(省略)
dependencies {
implementation ("com.squareup.retrofit2:retrofit:2.9.0")
implementation ("com.squareup.retrofit2:converter-gson:2.9.0")
testImplementation(kotlin("test"))
(省略)
}
プログラム
Main.kt
import model.Country
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import service.CountryService
import service.CountryServiceImpl
fun getAllCountriesUsingRetrofit(){
val countryService: CountryService =
CountryServiceImpl().getCountryServiceFactory()
val call: Call<List<Country>> = countryService.getAllCountries()
call.enqueue(object : Callback<List<Country>> {
override fun onResponse(call: Call<List<Country>>,
response: Response<List<Country>>
) {
response.body()?.forEach(::println)
}
override fun onFailure(call: Call<List<Country>>, t: Throwable) {
t.printStackTrace()
}
})
}
fun main(){
getAllCountriesUsingRetrofit()
}
model/Country.kt
package model
data class Country(var id: Number,
var countryName: String)
service/CountryService.kt
package service
import model.Country
import retrofit2.Call
import retrofit2.http.GET
interface CountryService {
@GET("/tmp/country_all.json")
fun getAllCountries(): Call<List<Country>>
}
service/CountryServiceImpl.kt
package service
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class CountryServiceImpl {
fun getCountryServiceFactory(): CountryService{
val retrofit = Retrofit.Builder()
.baseUrl("https://ekzemplaro.org")
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(CountryService::class.java)
}
}
実行結果
Country(id=18, countryName=Kenya)
Country(id=20, countryName=Tanzania)
Country(id=21, countryName=Ethiopia)
Country(id=22, countryName=Malawi)
Country(id=23, countryName=Country)
Country(id=24, countryName=Country)
Country(id=25, countryName=Kenya)
Country(id=26, countryName=Country)
Country(id=27, countryName=USA)
Country(id=28, countryName=USA)
Country(id=29, countryName=Kenya)
Country(id=30, countryName=Kenya)