RetrofitClient写接口、导包、配置、路径

一、前言

在 Spring Boot 项目中调用第三方 HTTP 接口,常见方案有 RestTemplate、HttpClient、Feign、WebClient 等。retrofit-spring-boot-starter 把 Square 的 Retrofit 封装成了 Spring Boot Starter,用「接口 + 注解」的方式声明式地调用 HTTP 接口,代码简洁,和 Spring 生态融合好,非常适合中小项目快速接入。

二、环境要求

项目 要求

JDK 1.8+

Spring Boot 1.4.2 ~ 2.x(对应 2.x 版本)

3.x / 4.x(对应 3.x / 4.x 版本)

构建工具 Maven / Gradle

网络 能访问目标接口

⚠️ 版本匹配很重要:Spring Boot 3.x 必须用 retrofit-spring-boot-starter 的 3.x 及以上版本,否则启动会报兼容性错误。

maven依赖

xml 复制代码
<dependency>
    <groupId>com.github.lianjiatech</groupId>
    <artifactId>retrofit-spring-boot-starter</artifactId>
    <version>3.0.2</version>
</dependency>

导包

java 复制代码
// 2.x 版本
import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient;

// 3.x / 4.x 版本
import com.github.lianjiatech.retrofit.spring.boot.core.RetrofitClient;

四、基本使用流程

4.1 配置文件里定义 baseUrl

xml 复制代码
# application.yml
http:
  remote-api: https://third-party-domain.com/api/device
  
@RetrofitClient 的 baseUrl 支持 ${} 占位符,会从 Spring 配置中读取。

4.2 定义请求体 VO

java 复制代码
@Data
public class DeviceListRequestVo {
    private String ip;
    private Integer currentPage;
    private Integer pageNum;
}

4.3 定义 Retrofit 接口

java

@RetrofitClient(baseUrl = "${http.remote-api}")

public interface RemoteDeviceService {

复制代码
@POST("list")
String getDeviceList(@Body DeviceListRequestVo vo);

}

4.4 在业务代码里注入使用

java

@Service

public class DeviceServiceImpl {

复制代码
@Resource
private RemoteDeviceService remoteDeviceService;

public Result<?> getDeviceList() {
    DeviceListRequestVo vo = new DeviceListRequestVo();
    vo.setIp("123");
    vo.setCurrentPage(1);
    vo.setPageNum(10);

    String result = remoteDeviceService.getDeviceList(vo);
    return Result.OK(result);
}

}

✅ Retrofit 接口会被自动扫描并注册为 Spring Bean,直接 @Resource / @Autowired 注入即可,不需要写实现类。

五、GET / POST 写法大全

5.1 GET 请求

(1)URL 固定参数 + 动态 Query 参数

java 复制代码
@GET("/api/report/getList.do?type=1&source=test&_search=false")
String getList(@Query("startTime") String startTime,
               @Query("endTime") String endTime);

(2)路径参数

java 复制代码
@GET("user/{id}")
String getUser(@Path("id") Long id);

5.2 POST 请求

(1)JSON 请求体(最常用)

java 复制代码
@POST("list")
String getDeviceList(@Body DeviceListRequestVo vo);

(2)表单提交 application/x-www-form-urlencoded

java 复制代码
@FormUrlEncoded
@POST("list")
String getDeviceList(@Field("ip") String ip,
                     @Field("currentPage") int currentPage,
                     @Field("pageNum") int pageNum);

⚠️ @FormUrlEncoded 和 @Body 不能同时使用。

(3)URL 查询参数 + JSON Body 混合

java 复制代码
@POST("report/list.do?type=1")
String getList(@Query("startTime") String startTime,
               @Query("endTime") String endTime,
               @Body SomeBody body);

5.3 参数注解对照表

注解 用途 出现位置

@Query | URL 查询参数 ?key=value | GET / POST 均可

@Path | 路径占位符 {id} | GET / POST 均可

@Body | JSON 请求体 | POST / PUT

@Field | 表单字段(需配 @FormUrlEncoded) | POST

@Header | 请求头 | 任意

@HeaderMap | 多个请求头 | 任意

六、⭐ 路径拼接规则(重点踩坑)

这是最容易出错的地方,必须搞清楚。

Retrofit 拼接 URL 遵循 RFC 3986 标准,@POST("...") 里的值会被当成相对 URL 用 HttpUrl.resolve() 解析。

规则总结

bash 复制代码
baseUrl	@POST 写法	最终 URL	结果
https://host/a/b/c	"list"	https://host/a/b/c/list	✅ 正确
https://host/a/b/c	"/list"	https://host/list	❌ 前缀被替换
https://host	"/a/b/c/list"	https://host/a/b/c/list	✅ 正确
https://host	"a/b/c/list"	https://host/a/b/c/list	✅ 正确

七、返回值处理

7.1 返回 String(原始响应)

java 复制代码
@POST("list")
String getDeviceList(@Body DeviceListRequestVo vo);

拿到的是原始 JSON 字符串,需要自己解析:

java 复制代码
String deviceList = remoteDeviceService.getDeviceList(vo);
JSONObject jsonObject = JSONObject.parseObject(deviceList);
JSONObject data = jsonObject.getJSONObject("data");
List<DeviceOnLineVo> records = data.getJSONArray("records").toJavaList(DeviceOnLineVo.class);

7.2 返回对象(推荐,自动反序列化)

java 复制代码
@POST("list")
ApiResponse<DevicePage> getDeviceList(@Body DeviceListRequestVo vo);

对应的类:

java 复制代码
@Data
public class ApiResponse<T> {
    private String code;
    private String message;
    private T data;
}

@Data
public class DevicePage {
    private List<DeviceOnLineVo> records;
    private long total;
    private long size;
    private long current;
    private long pages;
}

@Data
public class DeviceOnLineVo {
    private String udid;
    private String ip;
    private Integer onlineStatus;
}

7.3 各种返回类型对照

bash 复制代码
方法返回类型	得到的结果
String	原始响应体字符串
Result<T> / 实体类	自动反序列化后的对象
Call<String>	异步调用对象,需 enqueue
Response<String>	含状态码、响应头等完整响应
相关推荐
SL_staff1 小时前
MQTT Topic权限越界:JVS-IOT中系统Topic与自定义Topic的权责边界与验证实践
java·物联网·全栈
敲代码的瓦龙1 小时前
Jetpack?DataBinding!!!
android·java·开发语言·mysql·android-studio
斯维赤2 小时前
Spring AI | 结构化输出 & 多模态 一篇讲透
java·后端
程序员清风2 小时前
聊聊我的AI学习方法与思考!
java·后端·面试
RuoyiOffice2 小时前
SpringBoot+Vue3 节日主题换肤实战:一条参数换全站配色,节后自动还原
spring boot·vue3·spring boot 3·vben admin·ruoyi office·节日主题·换肤方案
AI深栈2 小时前
第 14 章 · LangGraph4j 入门:AI Agent 什么时候该上状态图
java·人工智能
摇滚侠2 小时前
《Spring Boot 3:高级与架构设计》第 2 章 IOC容器的高级机制 Environment 个人理解 4
java·spring boot·笔记·后端
zl_dfq2 小时前
Java学习1 之 【核心机制、程序基础结构、I/O】
java
青山木2 小时前
RocketMQ 入门到原理(六):可靠性全景
java·后端·中间件·架构·rocketmq