OkHttp的简单使用

首先引入okHttp依赖

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.12.0</version>
</dependency>

1. http client的创建

OkHttpClient httpclient = new OkHttpClient
                .Builder()
                .connectionPool(new ConnectionPool(50, 5, TimeUnit.MINUTES))//设置连接池
                .readTimeout(Duration.ofSeconds(2))//读取超时
                .connectTimeout(Duration.ofSeconds(2))//连接超时
                .writeTimeout(Duration.ofSeconds(2))//写入超时
                .build()

2. Request的创建

Request request = new Request
                .Builder()
                .header("key", KEY) //指定头部
                .url("https://www.baidu.com")//请求地址
                .tag(Long.class, 1L)//tag数据,可以在callback、response中获取
                .build();

3. 发送请求

1.发送同步请求

Response response = client.newCall(request).execute();

2.发送异步请求

        client.newCall(request).enqueue(new Callback() {


            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
            }
        });

4. tag的使用

在创建request的时候可以指定tag,在callback中取回tag

 public void onResponse(Call call, Response response) throws IOException {
        call.request().tag(Long.class);
    }

tag的实现是一个MapMap<Class<?>, Object> tags,在存入与获取时需要使用相同的Class

posted @ 2024-11-05 14:34  Hekk丶  阅读(346)  评论(0)    收藏  举报