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());
    }
}
相关推荐
天空鸟_时光不老6 分钟前
01-我不转Python把AI塞进Java里
java·人工智能·spring boot·后端·spring·spring cloud·架构
vx_Biye_Design18 分钟前
flask学生课程笔记共享系统29026-计算机课程设计、毕业设计
java·javascript·spring boot·后端·elasticsearch·flask·课程设计
代码山河19 分钟前
JDK、JRE、JVM的区别:一文讲清楚Java运行环境
java·学习·架构·教程·面向对象·项目
深入云栈32 分钟前
Netty 4.2.x 源码深度解析 (十七):Channel 底层读写 —— Unsafe 的 I/O 操作内核
java·后端·架构
SimonKing1 小时前
Qoder中Qwen3.8-Flash 限时免费使用
java·后端·程序员
云和数据.ChenGuang1 小时前
langchain4j InMemoryEmbeddingStore常用的方法
java·人工智能·windows·java-ee·fastapi·springai
雪雪爱冲浪1 小时前
ISP代理与住宅代理选型对比:从原理到实战
服务器·网络·网络协议·tcp/ip·接口隔离原则
智能直播1 小时前
OpenGL驱动的实时绿幕抠图:GPU着色器色度键控原理
运维·服务器
小番茄程序猿1 小时前
RAG 的 precision 只有 0.55,我以为检索烂了,MRR 一测才发现是我用错了尺子
java·后端
天空鸟_时光不老1 小时前
07-检查点与状态持久化
java·人工智能·spring boot·spring·spring cloud·kafka·maven