简体   繁体   中英

How to make a GET request from API that requires a Body and returns a boolean? Android/Kotlin/Retrofit

(For privacy purposes, I will be using very general terms)

Although I can make a GET request that takes in a body and returns a boolean successfully on Postman, as shown in this image Postman Screenshot , I can't get it to work for my Android app.

I have an API interface with the code:

@GET("api/is_correct")
    suspend fun isCorrect(
       @Body email: Email
    ): Response<Boolean>

and a method in my view model as shown below

fun checkIfCorrect(input: String) {
        val email = Email(input)
        viewModelScope.launch {
            try {
                val response = RetrofitInstance.api.isCorrect(email)
                Log.e(TAG, response.toString())
            } catch (e: Exception){
                Log.e(TAG, "error")
            }
        }
}

and this data class

data class Email (
    @SerializedName("email")
    val email: String
)

The log only prints out "error" when I call viewmodel.checkIfCorrect(...)

I've basically used the same process for all my other PUT, GET, and POST API calls. This is the only one that's causing trouble for me. I'm guessing it's because the response body for this particular api call isn't wrapped in { } and does not have a format like "result": true, the way other API responses do.

How can I fix this issue?

I've tried Response, Response, String, and Boolean as the return type for suspend fun isCorrect. I've also tried using Query("email") email: String and Path("email") email: String as the parameter for fun isCorrect even though my api endpoint does not require additional parameters in the URL, only the body.

If the api already exists there is not much you can do but try this as Retrofit may not support GET with body

        /**
         * import okhttp3.OkHttpClient
         * import okhttp3.Request
         * import okhttp3.RequestBody
         * import okhttp3.Response
         */
        val client = OkHttpClient().newBuilder()
            .build()
        val mediaType: MediaType = MediaType.parseMediaType("application/json")
        val body: RequestBody = RequestBody.create(mediaType, "{ \"message\":\"MESSAGE\"}")
        val request: Request = Request.Builder()
            .url("http://localhost:8080/sample/public")
            .method("GET", body)
            .addHeader("Content-Type", "application/json")
            .build()
        val response: Response = client.newCall(request).execute()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM