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>	含状态码、响应头等完整响应
相关推荐
栗子~~10 分钟前
java - logstash-logback-encoder 集成 demo
java·开发语言·logback
hmb↑22 分钟前
高并发与高可用技术经验
java·spring
楚识科技32 分钟前
XML配置OCR接入实战:自定义OCR模板从字段定义到API调用全流程
xml·java·ocr
code_slave(码畜)34 分钟前
微服务架构落地:消息队列架构设计(上篇)——异步解耦、削峰填谷,看懂业务事件流转本质
spring boot·spring cloud·微服务·云原生·架构
小蒜学长1 小时前
基于Java的公司采购系统的设计与实现(代码+数据库+LW)
java·数据库·spring boot·后端·公司采购系统
lee_tianbai1 小时前
Java SSM 电影票预定系统|完整前后端项目,开箱即用(源码分享)
java·开发语言·数据库
小坏讲微服务1 小时前
Spring Boot 4 新特性全解析:从上手到生产实战
java·spring boot·后端·架构·springboot4
砚底藏山河2 小时前
python量化入门:多周期数据对齐统一时间轴
java·数据库·python·金融·maven
集智飞行2 小时前
解决mavros2 ros2版本cpu占用高的问题
java·服务器·前端
鱼宵2 小时前
LangChain4j 结构化输出:让模型吐出 Java 对象,JSON 不再手写解析
java·开发语言·json·langchain4j