You need to enable JavaScript to run this app. 如何在Kotlin的Retrofit2中实现给定CURL请求的接口适配?
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 04:00:03