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());
    }
}
相关推荐
benbenAItalk4 小时前
数字人口播视频的批量生产实践:素材规范、任务编排与质量验收
java·前端·音视频
sunshine22 girl4 小时前
Java学习二 基本语法2, 算术运算符
java·学习
niucloud-admin5 小时前
JAVA V6 多商户商城 开发文档——插件目录结构
java·开发语言
我爱吃土豆15 小时前
AI 编程工具远程开发指南:Codex 桌面版与 WorkBuddy 通过 SSH 连接云服务器实践
服务器·人工智能·ssh
2601_962885725 小时前
如何用 Python 扫描 A 股跳空缺口并统计缺口回补概率?
java·前端·python
滕州市燕猫虎计算机科技工作室个体工商户5 小时前
Java锁
java·开发语言
一技安身5 小时前
【信创】银河麒麟V10、统信UOS解压7Z文件
linux·运维·服务器
shehuiyuelaiyuehao7 小时前
1计算机是如何工作的
java·计算机网络
Dawn-bit7 小时前
Linux 运维基础扩展:跳板机、堡垒机与物理服务器全流程
linux·运维·服务器·云计算·运维开发
新时代牛马7 小时前
Linux 定时任务:crontab、anacron 与systemd timer
linux·运维·服务器