OkHttp 使用教程

OkHttp 使用教程

okhttpAn HTTP+SPDY client for Android and Java applications.项目地址:https://gitcode.com/gh_mirrors/ok/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 支持响应缓存,可以避免重复获取相同的数据。

okhttpAn HTTP+SPDY client for Android and Java applications.项目地址:https://gitcode.com/gh_mirrors/ok/okhttp

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

罗蒙霁Ella

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

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

抵扣说明:

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

余额充值