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());
    }
}
相关推荐
张小洛15 小时前
Spring 常用类深度剖析(工具篇 04):CollectionUtils 与 Stream API 的对比与融合
java·后端·spring·spring工具类·spring utils·spring 类解析
一 乐16 小时前
房产租赁管理|基于springboot + vue房产租赁管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·房产租赁管理系统
xieliyu.16 小时前
Java顺序表实现扑克牌Fisher-Yates 洗牌算法
java·数据结构·算法·javase
YanDDDeat16 小时前
【Spring】事务注解失效与传播机制
java·后端·spring
℡終嚸♂68016 小时前
Vite 开发服务器文件读取 Writeup
运维·服务器·状态模式
SamDeepThinking16 小时前
学数据结构到底有什么用
java·后端·面试
Xiu Yan16 小时前
Java 转 C++ 系列:函数模板
java·开发语言·c++
程序员清风16 小时前
独立开发者必看:推荐几个可直接用的开源项目!
java·后端·面试
YJlio16 小时前
4月14日热点新闻解读:从金融数据到平台治理,一文看懂今天最值得关注的6个信号
java·前端·人工智能·金融·eclipse·电脑·eixv3
落魄江湖行16 小时前
基础篇三 一行 new String(“hello“) 到底创建了几个对象?90% 的人答错了
java·面试·八股文