JDK调用工具(二)

构建OkHttp请求

之前简单的介绍了OkHttp及基本的使用,下面介绍一下如何使用OkHttp创建目标请求对象。

1.1构建OkHttpClient

(1)构建简单的OkHttpClient

private static OkHttpClient createOkHttpClient1() {
        // 1、构建简单的OkHttpClient对象,使用默认配置
        return new OkHttpClient();
}

(2)构建复杂的OkHttpClient

private static OkHttpClient createOkHttpClient2() {
        // 2、构建复杂的的OkHttpClient对象,使用内置的Builder
        return new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS) // 读超时时间
                .writeTimeout(3, TimeUnit.SECONDS) // 写超时时间
                .connectTimeout(1, TimeUnit.SECONDS) // 连接超时时间
                .callTimeout(5, TimeUnit.SECONDS) // 响应超时时间
                .addInterceptor(new CustomInterceptor()) // 自定义拦截器
                .cache(new Cache(new File(""), 1024 * 1024 * 100)) // 自定义缓存,CacheInterceptor会使用
                .cookieJar(new CustomCookieJar()) // 自定义Cookie,BridgeInterceptor会使用
                .followRedirects(true) // 支持RetryAndFollowUpInterceptor的重定向
                .followSslRedirects(true) // 支持SSL重定向
                .retryOnConnectionFailure(true) // 支持RetryAndFollowUpInterceptor的重试
                .connectionPool(new ConnectionPool(10, 10, TimeUnit.SECONDS))
                // 自定义ConnectionPool,ConnectInterceptor会使用自定义ConnectionPool构建连接
                .build();
}

1.2 构建协议头

添加单个协议头可以通过addHeader

private static Request createRequest1() {
        return new Request.Builder()
                .url(EXAMPLE_URL)
                .addHeader("Authorization", "Bearer access_token")
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
}

移除协议头可以通过removeHeader

private static Request createRequest2() {
        return new Request.Builder()
                .url(EXAMPLE_URL)
                .addHeader("Authorization", "Bearer your_access_token")
                .removeHeader("User-Agent") // 移除 User-Agent 协议头
                .build();
}

替换协议头可以通过header,也可以通过Header对象批量替换和添加协议头

private static Request createRequest3() {
        Headers headers = new Headers.Builder()
                .add("Authorization", "Bearer your_access_token")
                .add("Content-Type", "application/json")
                .build();

        return new Request.Builder()
                .url(EXAMPLE_URL)
                .header("User-Agent", "OkHttp Example") // 替换或者添加单个
                .headers(headers) // 替换或者添加多个
                .build();

}

1.3 构建协议体

(1)表单

private static RequestBody createRequestBody1() {
        return new FormBody.Builder()
                .add("username", "john")
                .add("password", "password123")
                .build();
}

(2)JSON

private static RequestBody createRequestBody2() {
        String json = "{\"name\":\"xuyuan\", \"age\":25}";
        return RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));

}

​(3)复杂对象

private static RequestBody createRequestBody3() {
        User user = new User("xuyuan", 25);
        Gson gson = new Gson();
        String json = gson.toJson(user);
        return RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));

}

(4)文件​​​​​​

private static RequestBody createRequestBody4() {
        File file = new File(EXAMPLE_FILE_PATH);
        return new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(file, MediaType.parse("application/octet-stream")))
                .build();
}

1.4 构建请求对象

(1)GET请求

private static Request createRequest4() {
        Request getRequest = new Request.Builder()
                .url(EXAMPLE_URL)
                .get()
                .build();
        return getRequest;
}

(2)POST请求

private static Request createRequest5() {
        Request postRequest = new Request.Builder()
                .url(EXAMPLE_URL)
                .post(createRequestBody1())
                .build();
        return postRequest;
}

(3)定制化请求

private static Request createRequest6() {
        Headers headers = new Headers.Builder()
                .add("Authorization", "Bearer your_access_token")
                .add("Content-Type", "application/json")
                .build();

        return new Request.Builder()
                .url(EXAMPLE_URL)
                .post(createRequestBody1())
                .headers(headers)
                .cacheControl(CacheControl.FORCE_CACHE)
                .build();
}

1.5 注意事项

(1)Request 对象是不可变的,这意味着一旦创建后就不能直接修改。Request的newBuilder方法可以基于当前的Request对象获取一个新的Builder,继承上个Request的值。

(2)OkHttp 默认提供了连接池管理,但你也可以自定义连接池的大小和生命周期。合理地配置连接池可以提升网络请求的性能和效率。

(3)要注意响应的关闭和资源释放。

(4)在发送敏感数据时,务必使用 HTTPS。OkHttp 默认支持 HTTPS,并对 TLS 连接进行了良好的支持和管理。如果需要,可以自定义证书验证和安全配置。

(5)考虑使用 OkHttp 提供的缓存功能来优化网络请求的性能,避免不必要的重复请求。合理使用缓存可以减少网络流量和提升响应速度。

(6)在开发和调试过程中,启用 OkHttp 的日志功能可以帮助你查看详细的网络请求和响应信息,以便快速定位和解决问题。

  • 17
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小胖子许愿

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

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

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

打赏作者

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

抵扣说明:

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

余额充值