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());
    }
}
相关推荐
Loongproxy1 天前
2026年动态IP代理真实可用率怎么横评?爬虫选代理的关键是什么
服务器·网络·网络协议·tcp/ip
小蒜学长1 天前
vue旅游攻略网站(代码+数据库+LW)
java·数据库·vue.js·spring boot·后端·旅游
mengge.cloud1 天前
LVS 小白完整教程(Linux虚拟服务器负载均衡)
linux·运维·服务器·负载均衡·lvs
秦渝兴1 天前
LVS-DR 高可用集群实战:NFS + Web + DNS + Keepalived 全套架构
linux·服务器·网络·lvs
凤山老林1 天前
轻量级规则引擎落地:Spring Boot 集成 LiteFlow 实现动态业务编排与热更新
java·spring boot·后端·规则引擎·liteflow
夏贰四1 天前
管控数据加载调度如何规避任务冲突?数据加载运维监控体系该如何搭建?
java·大数据·运维
山甫aa1 天前
JavaWeb后端开发学习手册
java·开发语言·数据库·学习·mysql·springboot·web
鱼鳞_1 天前
热门八股-JVM
java·jvm
ly76891 天前
XML 从入门到实践:语法、命名空间、XPath、XSD 与 Java 安全解析
xml·java·python
Mortalbreeze1 天前
深入理解 TCP 协议(二):TCP 可靠传输与高效通信机制详解
linux·服务器·网络·网络协议·tcp/ip