Diego Cardenas
Diego Cardenas

Reputation: 55

Retrofit Headers and Body Kotlin

I have a question regarding retrofit. I am making a request to a service through POST, and I need to add Header and Body. What is the correct way to do it, or at least functional. I have tried with the following line without success.

interface Service{
    @Headers(
            "Accept: application/vnd.github.v3.full+json",
            "Token : {myToken}")
    @POST("pet/list")
    fun getPets(@Path("myToken")token: String, @Body body: TheBody): Call<PetList>
}
class TheBody(var userId: String,
              var auth: String)

Upvotes: 2

Views: 3151

Answers (1)

dreinoso
dreinoso

Reputation: 1689

Using interface and annotations you could do something like this

import com.google.gson.annotations.SerializedName
import io.reactivex.Single
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Path
import retrofit2.http.Query

interface MoviesApi {

    @GET("/key")
    fun  getKey(
            @Query("email") email: String)
            : Single<Dto.KeyResponse>

    @GET("/movies")
    fun  getMovies(
            @Header("api-key") apiKey: String, // DEFINE HEADER HERE
            @Query("page") page: Int,
            @Query("sort") sort: String,
            @Query("q") querySearch: String)
            : Single<List<Dto.MovieResponse>>

    sealed class Dto {
        data class KeyResponse(
                @SerializedName("key") val key: String,
                @SerializedName("email") val email: String
        ) : Dto()

        data class MovieResponse(
                @SerializedName("id") val id: Int,
                @SerializedName("title") val title: String,
                @SerializedName("description") val description: String,
                @SerializedName("image") val image: String
        ) : Dto()
    }
}

Upvotes: 2

Related Questions