OKHttp 是一个当前主流的网络请求的开源框架,由 Square 公司开发,用于替代 HttpUrlConnection 和 Apache HttpClient

特性
支持 HTTP2,对一台机器的所有请求共享同一个 Socket
内置连接池,支持连接复用,减少延迟
支持透明的 gzip 压缩响应体
通过缓存避免重复的请求
请求失败时自动重试主机的其他 IP,自动重定向
功能
PUTDELETEPOSTGET 等请求
文件的上传下载
加载图片 (内部会图片大小自动压缩)
支持请求回调,直接返回对象、对象集合
支持 Session 的保持
依赖

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.7.2</version>
</dependency>

测试请求

GET
测试 Get 请求

@Test
public void testGet() {
    String url = "https://www.baidu.com";
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
        .url(url)
        .build();
    Call call = client.newCall(request);
    try {
        Response response = call.execute();
        System.out.println(response.body().string());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

POST
测试 POST 请求

@Test
public void testPost() {
    String url = "http://localhost:9001/oauth/token";
    OkHttpClient client = new OkHttpClient();
    RequestBody body = new FormBody.Builder()
        .add("username", "admin")
        .add("password", "123456")
        .add("grant_type", "password")
        .add("client_id", "client")
        .add("client_secret", "secret")
        .build();
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    Call call = client.newCall(request);
    try {
        Response response = call.execute();
        System.out.println(response.body().string());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Last modification:July 9, 2020
如果觉得这篇技术文章对你有用,请随意赞赏