首页 > 解决方案 > 改造标题和正文 Kotlin

问题描述

我有一个关于改造的问题。我正在通过 POST 向服务发出请求,我需要添加 Header 和 Body。什么是正确的方法,或者至少是功能性的。我尝试了以下行但没有成功。

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)

标签: apikotlinretrofit2

解决方案


使用接口和注释你可以做这样的事情

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()
    }
}

推荐阅读