Retrofit框架调用第三方api

模板来源 豆包 时间 2026.3.29 19:49

一.引入依赖

复制代码
<dependency>
    <groupId>com.squareup.retrofit2</groupId>
    <artifactId>retrofit</artifactId>
    <version>2.9.0</version>
</dependency>
<dependency>
    <groupId>com.squareup.retrofit2</groupId>
    <artifactId>converter-gson</artifactId>
    <version>2.9.0</version>
</dependency>

二.写返回实体类

复制代码
@Data
@All~
@NO~
public class QuoteResponse {
    private String content;
    private String author;
}

三.写 Retrofit 配置类

复制代码
@Configuration
public class RetrofitConfig {
    public static final String BASE_URL = "https://api.quotable.io/";

    @Bean
    public Retrofit retrofit() { // 方法名随便取
        // 日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        // 自定义 OkHttp 客户端
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(30, TimeUnit.SECONDS)
                .build();

        // 构建 Retrofit
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();
    }
}

四.写 API 接口

复制代码
import retrofit2.Call;
import retrofit2.http.GET;
public interface QuoteApi {
    @GET("quotes/random")
    Call<QuoteResponse> getRandomQuote();
}

五.编写测试类

复制代码
import retrofit2.Call;
import retrofit2.Response;
public class ApiTest {
    public static void main(String[] args) throws Exception {
        // 1. 获取Retrofit实例
        Retrofit retrofit = RetrofitConfig.getInstance();
        // 2. 创建接口代理对象
        QuoteApi quoteApi = retrofit.create(QuoteApi.class);
        // 3. 获得请求包裹Call
        Call<QuoteResponse> call = quoteApi.getRandomQuote();
        // 4. 发送请求,得到完整响应Response
        Response<QuoteResponse> response = call.execute();
        // 5. 取出响应体(数据对象)
        QuoteResponse result = response.body();
        // 输出
        System.out.println("名言:" + result.getContent());
        System.out.println("作者:" + result.getAuthor());
    }
}
相关推荐
xqqxqxxq1 天前
Java AI智能P图工具技术笔记
java·人工智能·笔记
谷雨不太卷1 天前
进程的状态码
java·前端·算法
顾温1 天前
default——C#/C++
java·c++·c#
空中海1 天前
02 ArkTS 语言与工程规范
java·前端·spring
楚国的小隐士1 天前
在AI时代,如何从0接手一个项目?
java·ai·大模型·编程·ai编程·自闭症·自闭症谱系障碍·神经多样性
island13141 天前
【C++仿Muduo库#3】Server 服务器模块实现上
服务器·开发语言·c++
yaki_ya1 天前
yaki-C语言:从概念基础到内存解析---数组(array)完全指南
java·c语言·算法
刃神太酷啦1 天前
扒透 STL 底层!map/set 如何封装红黑树?迭代器逻辑 + 键值限制全手撕----《Hello C++ Wrold!》(23)--(C/C++)
java·c语言·javascript·数据结构·c++·算法·leetcode
亚历克斯神1 天前
Java 25 模式匹配增强:让代码更简洁优雅
java·spring·微服务
星辰徐哥1 天前
Rust异步测试与调试的实践指南
android·java·rust