api - 改造标题和正文 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)
解决方案
使用接口和注释你可以做这样的事情
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()
}
}
推荐阅读
- visual-studio-code - 为什么我只能连接到三台服务器中的两台?
- python - 如何控制 Tkinter 网格中的标签位置和间距
- python-3.x - 从带有列的 json 响应创建数据框(all_urls、描述、名称、价格)
- javascript - React.js - 完成了呈现所有项目的 API 提取,现在我希望能够使用 JSON 信息将每个项目路由到他们的“自己的”页面
- java - 计算 JTextArea 中字符的出现次数
- set - 如何有效地找到集合和整数的最大 gcd?
- r - R中时间序列中的变化点检测
- r - R中具有函数的滞后值多列
- javascript - Firestorage 在硬编码时有不同的行为
- python - MatPlotLib Scatter 在函数内部不起作用