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>	含状态码、响应头等完整响应
相关推荐
从琳开始98912 小时前
从Socket到UDP回显服务器:Java网络编程完整指南
java·网络·网络协议·udp·java-ee
软件技术NINI12 小时前
基于SpringBoot和Vue的摇滚乐鉴赏网站
vue.js·spring boot·后端·spring·html·毕业设计·毕设
西瓜拿铁好喝12 小时前
开源和闭源 AI 办公工具,分别适合谁
java·前端·数据库
学长毕设12 小时前
基于SpringBoot的校园礼服租赁系统的设计与实现
java·spring boot·后端
明天也要努力学习12 小时前
深入理解 JVM 垃圾回收(GC)
java·jvm
golang学习记12 小时前
IDEA 断点调试技巧:拖拽
java·ide·intellij-idea
Sayai12 小时前
Flink 日志解析任务性能优化实战:正则/Grok 预编译、Guava 缓存权重陷阱与 ES 写入隔离
java·大数据·性能优化·flink·实时计算
计算机毕设定制辅导-无忧学长12 小时前
《基于物品协同过滤的闲置书换购微信小程序设计开发》
java·vue.js·spring boot·微信小程序·uniapp·闲置书换购微信小程序·物品协同过滤算法
Best_Liu~12 小时前
SpringBoot全局日期格式化
java·spring boot·后端
少年的范儿13 小时前
IntelliJ IDEA 配置 JDK 21 与 Maven 教程(Windows):开发环境配置与验证
java·jdk·maven·intellij idea