SpringBoot 整合okHttp3 okhttp3用法 okhttp整合 okhttp用法 SpringBoot 整合okHttp3

这篇具有很好参考价值的文章主要介绍了SpringBoot 整合okHttp3 okhttp3用法 okhttp整合 okhttp用法 SpringBoot 整合okHttp3。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1、引入Maven依赖

        <!--okhttp3 依赖-->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.3</version>
        </dependency>

2、发起请求 (同步)

2.1、GET请求

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
        .url("http://www.example.com/api/resource?q=123123")
        .header("token", "qweqweasd123123123")
        .build();

try {
    Response response = client.newCall(request).execute();
    
    if (response.isSuccessful()) {
        String responseBody = response.body().string();
        System.out.println(responseBody);
    } else {
        System.out.println("请求失败,错误码:" + response.code());
    }
} catch (IOException e) {
    e.printStackTrace();
}

GET 请求需要传递 application/json参数

       OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/json");
        String jsonBody = "{\"key\": \"value\"}";

        // 创建请求体
        RequestBody requestBody = RequestBody.create(jsonBody, mediaType);

        // 创建GET请求并携带请求体
        Request request = new Request.Builder()
                .url("http://example.com/api/endpoint")
                .get()
                .header("Content-Type", "application/json")
                .method("GET", requestBody)
                .build();

        try {
            // 发送请求并获取响应
            Response response = client.newCall(request).execute();
            // 处理响应...
        } catch (IOException e) {
            e.printStackTrace();
        }

2.2、POST请求

String jsonData = "{\"name\": \"lizr\"}";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("http://www.example.com/api/resource")
        .post(RequestBody.create(jsonData.getBytes(), MediaType.parse("application/json")))
        .header("token", "qweqweasd123123123")
        .build();

try {
    Response response = client.newCall(request).execute();
    
    if (response.isSuccessful()) {
        String responseBody = response.body().string();
        System.out.println(responseBody);
    } else {
        System.out.println("请求失败,错误码:" + response.code());
    }
} catch (IOException e) {
    e.printStackTrace();
}

2.3、PUT请求

String jsonData = "{\"name\": \"lizr\"}";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("http://www.example.com/api/resource")
        .put(RequestBody.create(jsonData.getBytes(), MediaType.parse("application/json")))
        .header("token", "qweqweasd123123123")
        .build();

try {
    Response response = client.newCall(request).execute();
    
    if (response.isSuccessful()) {
        String responseBody = response.body().string();
        System.out.println(responseBody);
    } else {
        System.out.println("请求失败,错误码:" + response.code());
    }
} catch (IOException e) {
    e.printStackTrace();
}

2.4、DELETE请求

String jsonData = "{\"name\": \"lizr\"}";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("http://www.example.com/api/resource")
        .delete(RequestBody.create(jsonData.getBytes(), MediaType.parse("application/json")))
        .header("token", "qweqweasd123123123")
        .build();

try {
    Response response = client.newCall(request).execute();
    
    if (response.isSuccessful()) {
        String responseBody = response.body().string();
        System.out.println(responseBody);
    } else {
        System.out.println("请求失败,错误码:" + response.code());
    }
} catch (IOException e) {
    e.printStackTrace();
}

3、发起请求 (异步)

3.1、GET请求

OkHttpClient client = new OkHttpClient();

String url = "https://example.com/api/user";

Request request = new Request.Builder()
        .url(url)
        .header("token", "qweqweasd123123123")
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // 处理响应数据
        String responseBody = response.body().string();
        System.out.println(responseBody);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        // 处理请求失败情况
        e.printStackTrace();
    }
});

3.2、POST请求

OkHttpClient client = new OkHttpClient();

String url = "https://example.com/api/user";
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String requestBody = "{\"username\":\"john\", \"password\":\"123456\"}";


RequestBody body = RequestBody.create(mediaType, requestBody);

Request request = new Request.Builder()
        .url(url)
        .post(body)
        .header("token", "qweqweasd123123123")
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // 处理响应数据
        String responseBody = response.body().string();
        System.out.println(responseBody);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        // 处理请求失败情况
        e.printStackTrace();
    }
});

3.3、PUT请求

OkHttpClient client = new OkHttpClient();

String url = "https://example.com/api/user";
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String requestBody = "{\"username\":\"john\", \"password\":\"123456\"}";


RequestBody body = RequestBody.create(mediaType, requestBody);

Request request = new Request.Builder()
        .url(url)
        .put(body)
        .header("token", "qweqweasd123123123")
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // 处理响应数据
        String responseBody = response.body().string();
        System.out.println(responseBody);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        // 处理请求失败情况
        e.printStackTrace();
    }
});

3.4、DELETE请求

OkHttpClient client = new OkHttpClient();

String url = "https://example.com/api/user";
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String requestBody = "{\"username\":\"john\", \"password\":\"123456\"}";


RequestBody body = RequestBody.create(mediaType, requestBody);

Request request = new Request.Builder()
        .url(url)
        .delete(body)
        .header("token", "qweqweasd123123123")
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // 处理响应数据
        String responseBody = response.body().string();
        System.out.println(responseBody);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        // 处理请求失败情况
        e.printStackTrace();
    }
});

4、连接池

可以使用连接池来管理和复用HTTP和HTTPS连接,以提高性能和效率

// 创建连接池对象
ConnectionPool connectionPool = new ConnectionPool(5, 10, TimeUnit.MINUTES);

// 创建OkHttpClient并设置连接池
OkHttpClient client = new OkHttpClient.Builder()
        .connectionPool(connectionPool)
        .build();

// 创建请求对象
Request request = new Request.Builder()
        .url("http://www.example.com")
        .build();

try {
    // 发送请求并获取响应
    Response response = client.newCall(request).execute();

    if (response.isSuccessful()) {
        String responseBody = response.body().string();
        System.out.println(responseBody);
    } else {
        System.out.println("请求失败,错误码:" + response.code());
    }
} catch (IOException e) {
    e.printStackTrace();
}

上述代码中,通过创建ConnectionPool对象,并将其设置到OkHttpClient中,从而启用了连接池功能。ConnectionPool的构造函数接受三个参数:maxIdleConnections、keepAliveDuration和timeUnit,用于配置连接池的最大空闲连接数、连接保持时间以及时间单位。

连接池会自动管理和复用连接,适当地回收和关闭空闲的连接。这样可以避免频繁地创建和关闭连接,提高性能和效率,特别是在多次请求同一主机时。

合理地设置连接池参数非常重要,以符合你的实际需求。可以根据并发请求的数量、目标服务器的负载能力以及网络环境等因素来调整连接池的大小和保持时间。

有关更多详细信息和高级用法,建议参考 okhttp3 的官方文档或其他相关资料。文章来源地址https://www.toymoban.com/news/detail-556707.html

到了这里,关于SpringBoot 整合okHttp3 okhttp3用法 okhttp整合 okhttp用法 SpringBoot 整合okHttp3的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java之okhttp3请求方式

    在java开发中,发起http请求是非常常见的需求,常用的有HttpClient,下面聊一下okhttp3的请求方式。 1、引入okhttp3依赖 2、提供springboot工程及http接口 3、http请求 4、请求结果 get请求 post请求 form表单请求 可见发起http请求还是挺方便的,感兴趣的小伙伴可以试试~~~///( v )~~~

    2024年02月13日
    浏览(31)
  • Android Okhttp3 分发器源码解析

    在 OkHttp 中,分发器(Dispatcher)是负责调度和执行网络请求的组件。它 管理 着 并发 的 请求数量 以及请求的 优先级 ,确保合理地使用底层的连接池和线程池,从而 提高 网络请求的 效率 和 性能 。 默认情况下,OkHttp 使用一个单例的分发器,它可以处理同时进行的最大请求

    2024年02月12日
    浏览(37)
  • com.squareup.okhttp3:okhttp 组件安全漏洞及健康度分析

    维护者 square组织 许可证类型 Apache License 2.0 首次发布 2016 年 1 月 2 日 最新发布时间 2023 年 4 月 23 日 GitHub Star 44403 GitHub Fork 9197 依赖包 5,582 依赖存储库 77,217 com.squareup.okhttp3:okhttp 一个开源的 HTTP 客户端库,可以用于 Android 和 Java 应用程序。它提供了一种简单而强大的方式来发

    2024年02月10日
    浏览(17)
  • Android okhttp3.0配置https信任所有证书

    参考: Android okhttp3.0配置https的自签证书和信任所有证书

    2024年02月19日
    浏览(31)
  • Android Okhttp3添加https自签名证书以及Glide4

    没有得到安卓认可的证书颁发机构颁发的证书. 自己颁发的证书, 分临时性的(在开发阶段使用)或在发布的产品中永久性使用的两种. 而只有Android系统认可的机构办法的证书,在使用过程中才不会出现安全提示。 为什么会有人使用自签名的证书呢? (重要的事重复三遍)免费

    2024年04月16日
    浏览(67)
  • 在Java版的OkHttp3 中 RequestBody.create() 过时解决方案

    当使用下面的代码时会提示 RequestBody.create() 已过时。 如下图: 解决办法: 如下图:

    2024年02月16日
    浏览(30)
  • Android Okhttp3添加https自签名证书以及Glide4,Android高级工程师进阶学习—Android热修复原理

    二、自签名证书 什么是自签名证书(self-signed certicates)? 自签名证书就是没有通过受信任的证书颁发机构, 自己给自己颁发的证书. SSL 证书大致分三类: 由安卓认可的证书颁发机构CA(Certificate Authority)(如: VeriSign、DigiCert), 或这些机构的下属机构颁发的证书. 没有得到安卓认可的

    2024年04月17日
    浏览(29)
  • Okhttp在SpringBoot中的应用,太强了

    目录 一、okhttp是什么 二、为什么需要用到okhttp 三、okhttp整合springboot的方式   OkHttp是一个开源的Java/Android HTTP客户端库,它由Square公司开发并维护 。OkHttp的目标是成为一个快速、高效、可扩展且易于使用的HTTP客户端库,为Android应用程序提供网络访问的支持。 使用OkHttp, 我

    2024年02月12日
    浏览(26)
  • springboot引入minio导致的okhttp、kotlin的版本冲突问题

    问题背景 项目中需要引入minio,添加了如下依赖 结果运行报错: 解决过程 1. 看到 Unsupported OkHttp library found. Must use okhttp = 4.8.1 ,以为是之前引入的okhttp的版本太低,于是将   okhttp  升到   4.8.1  ,还是报同样错误 2. 上网查了一下,说需要在minio的依赖中排除okhttp依赖,再引

    2024年04月26日
    浏览(24)
  • okhttp下载文件 Java下载文件 javaokhttp下载文件 下载文件 java下载 okhttp下载 okhttp

    示例 http客户端 用的是 okhttp,也可以用 UrlConnetcion或者apache okhttp官网 也可以下载 okhttp jar方式引入 1.1、okhttp发起请求官网Demo 3.1读写内容

    2024年02月12日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包