You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Retrofit 2如何在发送数据前查看请求值与结构?

当然可以用System.out.print来查看请求数据,但其实这只是一种基础方式,还有更高效、能看到完整请求全貌的方法——我来给你详细讲讲两种方式的用法:

一、用System.out.print快速查看请求实体

如果你只是想确认自己准备发送的请求实体的结构和值,完全可以在调用Retrofit接口前,把请求对象转成JSON字符串打印出来。比如用Gson来序列化:

// 假设你的请求实体类是UserRequest
UserRequest request = new UserRequest("JohnDoe", "john@example.com");
// 转成JSON并打印
System.out.println("待发送的请求数据: " + new Gson().toJson(request));

// 再调用Retrofit接口
yourApiService.submitUser(request);

不过这种方式有个局限:它只能看到你本地构造的对象,看不到Retrofit实际发送给服务器的完整请求(比如自动添加的请求头、URL参数编码、表单字段拼接后的结果等)。

二、用OkHttp拦截器查看完整请求(推荐)

这是Retrofit官方推荐的调试方式,能捕获到实际发送的全部请求内容,包括URL、请求方法、请求头、请求体,甚至响应数据。

方式1:自定义日志拦截器

自己写一个简单的拦截器,按需打印内容:

public class RequestLoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        // 获取原始请求
        Request request = chain.request();
        
        // 打印请求基本信息
        System.out.println("=== 请求开始 ===");
        System.out.println("请求URL: " + request.url());
        System.out.println("请求方法: " + request.method());
        System.out.println("请求头: " + request.headers());
        
        // 打印请求体(如果存在)
        if (request.body() != null) {
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            String requestBody = buffer.readUtf8();
            System.out.println("请求体: " + requestBody);
        }
        
        // 执行请求并记录耗时
        long startTime = System.nanoTime();
        Response response = chain.proceed(request);
        long durationMs = (System.nanoTime() - startTime) / 1_000_000;
        
        // 打印响应信息(可选)
        System.out.println("=== 响应结果 ===");
        System.out.println("响应状态码: " + response.code());
        System.out.println("请求耗时: " + durationMs + "ms");
        // 注意:调用response.body().string()后会消耗body,需要重新构建响应
        String responseBody = response.body().string();
        System.out.println("响应体: " + responseBody);
        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), responseBody))
                .build();
    }
}

然后把这个拦截器添加到OkHttpClient,再关联到Retrofit:

OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .addInterceptor(new RequestLoggingInterceptor())
        .build();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("你的基础URL")
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

方式2:用官方的HttpLoggingInterceptor(更省心)

OkHttp提供了现成的日志拦截器,不用自己写代码,功能更完善:

  1. 先添加依赖(以Gradle为例):
implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
  1. 配置并使用拦截器:
// 创建日志拦截器,指定打印的目标(这里用System.out)
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> 
        System.out.println("OkHttp 日志: " + message)
);
// 设置日志级别:BODY级别会打印请求和响应的完整内容
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

// 添加到OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .addInterceptor(loggingInterceptor)
        .build();

// 构建Retrofit时使用这个OkHttpClient
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("你的基础URL")
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

这样每次请求都会自动打印完整的日志,包括请求的所有细节,非常适合调试。

总结

  • 用System.out.print可以快速查看本地构造的请求实体,但看不到实际发送的完整请求;
  • 更推荐用OkHttp拦截器,不管是自定义还是官方提供的,都能全面掌握请求和响应的所有信息,调试效率更高。

内容的提问来源于stack exchange,提问作者Aditya Pranav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:19:14