如何在Kotlin的Retrofit2中实现给定CURL请求的接口适配?
CURL请求转Retrofit接口实现方案
1. 先拆解目标CURL的请求要素
你给出的CURL对应请求参数如下:
- 请求方式:POST
- 接口地址:
https://builder.pingpong.us/api/builder/1ca62a123185a612324ef24/integration/v0.2/custom/5d234ee2134aef2123 - 请求头:
Authorization: Basic auth-token(身份校验头)Content-Type: application/json(请求体格式为JSON)
- 请求体JSON结构:
{ "request": { "query": "HI" } }
2. 定义请求体实体类
以下以Kotlin为例,Java场景下编写对应带Getter/Setter的JavaBean即可:
// 外层请求实体 data class ChatRequest( val request: InnerQuery ) // 内层请求参数实体 data class InnerQuery( val query: String )
3. 编写Retrofit服务接口
interface PingPongApi { // 拼接baseUrl之外的剩余路径即可 @POST("api/builder/1ca62a123185a612324ef24/integration/v0.2/custom/5d234ee2134aef2123") fun sendChatRequest( // 动态传入Authorization头,固定值也可直接写死 @Header("Authorization") auth: String = "Basic auth-token", // 传入JSON请求体,Retrofit会自动序列化 @Body request: ChatRequest ): retrofit2.Response<YourResponseBean> // 这里YourResponseBean要替换为接口实际返回值对应的实体类 }
4. 初始化Retrofit并发起请求
// 初始化Retrofit实例,指定baseUrl val retrofit = Retrofit.Builder() .baseUrl("https://builder.pingpong.us/") // 添加JSON序列化转换器,这里用Gson,也可替换为Moshi等其他转换器 .addConverterFactory(GsonConverterFactory.create()) .build() // 创建API服务实例 val apiService = retrofit.create(PingPongApi::class.java) // 构造请求参数发起请求 val requestParam = ChatRequest(InnerQuery("HI")) val response = apiService.sendChatRequest(body = requestParam)
注意事项
- 实际使用时要将
auth-token替换为你自己的有效身份凭证 - 如果Authorization是所有接口通用的请求头,可直接通过OkHttp拦截器统一添加,无需每个接口单独配置
- 返回结果实体类
YourResponseBean需要根据该接口实际返回的JSON结构自行定义
内容的提问来源于stack exchange,提问作者lee yes
相关产品推荐
相关产品推荐

