OkHttp 使用教程

OkHttp 使用教程

项目介绍

OkHttp 是一个高效的 HTTP 客户端,广泛应用于 Java 和 Android 应用程序中。它由 Square 公司开发,旨在提供更快的资源加载速度和节省带宽。OkHttp 支持 HTTP/2、连接池、GZIP 压缩、响应缓存等特性,能够从常见的连接问题中无声恢复,并支持现代 TLS 功能。

项目快速启动

安装 OkHttp

首先,在项目的 build.gradle 文件中添加 OkHttp 依赖:

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.3'
}

发送 GET 请求

以下是一个简单的示例,展示如何使用 OkHttp 发送 GET 请求并获取响应:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class OkHttpExample {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://api.example.com/data")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                System.out.println(response.body().string());
            } else {
                System.out.println("Request failed: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

发送 POST 请求

以下是一个示例,展示如何使用 OkHttp 发送 POST 请求并传递 JSON 数据:

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;

public class OkHttpPostExample {
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        String json = "{\"key\":\"value\"}";
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url("https://api.example.com/data")
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                System.out.println(response.body().string());
            } else {
                System.out.println("Request failed: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

应用案例和最佳实践

使用拦截器进行日志记录

拦截器是 OkHttp 中一个强大的功能,可以用于在请求和响应过程中插入自定义逻辑。以下是一个简单的拦截器示例,用于记录请求和响应的详细信息:

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class LoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        long t1 = System.nanoTime();
        System.out.println(String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers()));

        Response response = chain.proceed(request);

        long t2 = System.nanoTime();
        System.out.println(String.format("Received response for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers()));

        return response;
    }
}

在 OkHttpClient 中使用该拦截器:

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(new LoggingInterceptor())
        .build();

使用缓存减少服务器负载

OkHttp 支持响应缓存,可以避免重复获取相同的数据。

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值