ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 레트로핏 api 호출 기본 예제
    kotlin 2024. 2. 25. 00:32

     

     

    해당 코드는 연습용으로..

    메인액티비티는 코틀린이 아니라 플러터를 사용하고있음..

     

     

    메인 액티비티



    class MainActivity : FlutterActivity() {
    var funcCollection = Functions

    private val CHANNEL = "samples.flutter.dev/test"


    @RequiresApi(VERSION_CODES.P)
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    MethodChannel(
    flutterEngine.dartExecutor.binaryMessenger,
    CHANNEL
    ).setMethodCallHandler { call, result ->
    if (call.method == "getdata") {

    getData()

    }
    }
    }



    fun getData() {
    try {
    val callApi : Call<List<DataResponse>> = RetrofitClient.apiService.getData(7)

    callApi.enqueue(object : Callback<List<DataResponse>> {
    override fun onResponse(call: Call<List<DataResponse>>, response: Response<List<DataResponse>>) {

    if (response.isSuccessful) {

    val dataResponse: List<DataResponse>? = response.body()

    print("dataResponse : ${dataResponse}")

    } else {
    println("Request failed: ${response.code()}")
    println("Request failed: ${response.toString()}")
    }

    }

    override fun onFailure(call: Call<List<DataResponse>>, t: Throwable) {
    println("onFailure >> Request failed: ${t.message}")
    }
    })
    } catch(e : Exception) {
    println ("catch Exception e : ${e}")

    }


    }
    }


     

     

    interface apiService 

     

     


    import retrofit2.Call
    import retrofit2.http.GET
    import retrofit2.http.Path
    import retrofit2.http.Query

    interface ApiService {

    // @GET("quotes")
    // fun getData(@Query("param") param: Int): Call<List<DataResponse>>

    @GET("quotes/{id}")
    fun getData(@Path("id") param: Int): Call<List<DataResponse>>


    }

     

     

    데이터 클래스

     


    data class DataResponse(


    @SerializedName("quote") val quote: String,
    @SerializedName("author") val author: String

    )

     

     

     

    레트로핏 클라이언트

     



    import ApiService
    import retrofit2.Retrofit
    import retrofit2.converter.gson.GsonConverterFactory


    object RetrofitClient {



    private const val BASE_URL = "https://api.breakingbadquotes.xyz/v1/"

    // Retrofit 인스턴스를 초기화합니다.
    private val retrofit = Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create()) // Gson Converter를 추가합니다.
    .build()

    // Retrofit을 사용하여 API 서비스를 생성합니다.
    val apiService: ApiService = retrofit.create(ApiService::class.java)
    }

     

     

    @Parh 어노테이션을 안써봐서 구글링하느라 시간을 좀 보냈다.

    동적 Uri 할당할때 사용.

     

    챗 gpt 에 물어서 서비스 키 없이 호출하고 응답할수있는 공개 api 찾느라 삽질좀함 ㅋㅋ

    브레이킹배드의 대사란다..

    'kotlin' 카테고리의 다른 글

    flutter -> kotlin 함수 호출  (0) 2021.10.19
Designed by Tistory.