14079_Z
14079_Z

Reputation: 447

Retrofit2 POST request with body as parameter Kotlin

I'm new to Kotlin and having trouble to change the existing POST request parameters to body instead. I looked at other answers but none of them have the similar code as mine for the request part. I don't know how to change it just getting a lot of syntax errors. Thanks!

import retrofit2.Call
import retrofit2.http.*

interface PostInterface {
    @POST("signin")
    fun signIn(@Query("email") email: String, @Query("password") password: String): Call<String>
}


class BasicRepo @Inject constructor(val postInterface: PostInterface) {

   fun signIn(email: String, password: String): MutableLiveData<Resource> {
       val status: MutableLiveData<Resource> = MutableLiveData()
       status.value = Resource.loading(null)
       postInterface.signIn(email, password).enqueue(object : Callback<String> {
           override fun onResponse(call: Call<String>, response: Response<String>) {
                 if (response.code() == 200 || response.code() == 201) {
                     // do something
                 } else {
                    // do something
                 }
            }
        }
     }
}

class User constructor(
    email: String,
    password: String
) 

Upvotes: 1

Views: 3578

Answers (2)

MEGHA RAMOLIYA
MEGHA RAMOLIYA

Reputation: 1917

 1. First, in the APIService.kt file add the following @POST annotation:
interface APIService {
    // ...

    @POST("/api/v1/create")
    suspend fun createEmployee(@Body requestBody: RequestBody): Response<ResponseBody>

    // ...
}

 2. the POST request will look like this:

private fun callLogIn(type: String, email: String, password: String){

    // Create Retrofit
    val retrofit = Retrofit.Builder()
        .baseUrl(CONST.BASE_URL)
        .build()

    // Create Service
    val service = retrofit.create(APIService::class.java)

    // Create JSON using JSONObject
    val jsonObject = JSONObject()
    jsonObject.put("login_id", email)
    jsonObject.put("password", password)

    // Convert JSONObject to String
    val jsonObjectString = jsonObject.toString()

 
    val requestBody = jsonObjectString.toRequestBody("application/json".toMediaTypeOrNull())

    CoroutineScope(Dispatchers.IO).launch {
        // Do the POST request and get response
        val response = service.createEmployee(requestBody)

        withContext(Dispatchers.Main) {
            if (response.isSuccessful) {

                // Convert raw JSON to pretty JSON using GSON library
                val gson = GsonBuilder().setPrettyPrinting().create()
                val prettyJson = gson.toJson(
                    JsonParser.parseString(
                        response.body()
                            ?.string() 
                    )
                )
                
                Log.d(" JSON :", prettyJson)

            } else {

                Log.e("mytag", response.code().toString())

            }
        }
    }
}

Upvotes: 0

imn
imn

Reputation: 890

@POST("signin")
suspend fun signIn(
    @Body body: User,
): ResponseBody

Btw, You can use body instead of query params only if your API supports it. Also, I recommend using a ResultWrapper. Handling errors with Retrofit and Coroutines in a single place

Upvotes: 1

Related Questions