Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.3 kB
3
Indexable
Never
Define Data Classes:
Create data classes to represent the expected response structure:
kotlin
Copy code
data class DoorResponse(
    val action: String,
    val result: String
)
Create Retrofit Service:
Define a Retrofit service interface with the API method:
kotlin
Copy code
import retrofit2.Call
import retrofit2.http.GET

interface ApiService {
    @GET("/cgi-bin/ConfigManApp.com?key=F_LOCK&code=8008")
    fun openDoor(): Call<DoorResponse>
}
Create Retrofit Client:
Create a Retrofit client instance:
kotlin
Copy code
import okhttp3.Credentials
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object ApiClient {
    private const val BASE_URL = "http://172.16.54.30"

    val service: ApiService by lazy {
        val okHttpClient = OkHttpClient.Builder()
            .addInterceptor { chain ->
                val credentials = Credentials.basic("admin", "admin")
                val request = chain.request().newBuilder()
                    .header("Authorization", credentials)
                    .build()
                chain.proceed(request)
            }
            .build()

        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiService::class.java)
    }
}
Make API Call:
Use the Retrofit service to make the API call:
kotlin
Copy code
val apiService = ApiClient.service
val call = apiService.openDoor()

call.enqueue(object : Callback<DoorResponse> {
    override fun onResponse(call: Call<DoorResponse>, response: Response<DoorResponse>) {
        if (response.isSuccessful) {
            val doorResponse = response.body()
            if (doorResponse != null) {
                val action = doorResponse.action
                val result = doorResponse.result
                // Handle the action and result
                if (action == "open door" && result == "success") {
                    // Handle success case
                } else {
                    // Handle other cases
                }
            }
        } else {
            // Handle error response
        }
    }

    override fun onFailure(call: Call<DoorResponse>, t: Throwable) {
        // Handle the failure
    }
})