java.net.http.HttpClient使用示例解析

 更新时间:2023年08月31日 09:53:40   作者:supermassive  
这篇文章主要为大家介绍了java.net.http.HttpClient使用示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

java自带HttpClient使用

在使用java自带的HttpClient时, 发现一个现象,即有些以前常用http的header, 是不能够set到请求里进行传递的,在jdk.internal.net.http.common.Utils类中,可以看到

private static Set<String> getDisallowedHeaders() {
        Set<String> headers = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        headers.addAll(Set.of("connection", "content-length", "expect", "host", "upgrade"));
        String v = getNetProperty("jdk.httpclient.allowRestrictedHeaders");
        if (v != null) {
            // any headers found are removed from set.
            String[] tokens = v.trim().split(",");
            for (String token : tokens) {
                headers.remove(token);
            }
            return Collections.unmodifiableSet(headers);
        } else {
            return Collections.unmodifiableSet(headers);
        }
    }

connection, content-length, expect, host, upgrade这几个, 属于禁止设置的。

校验

因为在jdk.internal.net.http.HttpRequestBuilderImpl中, 会进行严格的校验

private void checkNameAndValue(String name, String value) {
        requireNonNull(name, "name");
        requireNonNull(value, "value");
        if (!isValidName(name)) {
            throw newIAE("invalid header name: \"%s\"", name);
        }
        if (!Utils.ALLOWED_HEADERS.test(name, null)) {
            throw newIAE("restricted header name: \"%s\"", name);
        }
        if (!isValidValue(value)) {
            throw newIAE("invalid header value: \"%s\"", value);
        }
    }

控制连接复用

它自己控制连接的复用,所以设置不了connection这个header.从jdk.internal.net.http.ConnectionPool中可以看出一些参数

static final long KEEP_ALIVE = Utils.getIntegerNetProperty(
            "jdk.httpclient.keepalive.timeout", 1200); // seconds
static final long MAX_POOL_SIZE = Utils.getIntegerNetProperty(
            "jdk.httpclient.connectionPoolSize", 0); // unbounded

jdk.internal.net.http.HttpConnection

从jdk.internal.net.http.HttpConnection中可以看到连接如何放入池中

/**
     * Forces a call to the native implementation of the
     * connection's channel to verify that this channel is still
     * open.
     * <p>
     * This method should only be called just after an HTTP/1.1
     * connection is retrieved from the HTTP/1.1 connection pool.
     * It is used to trigger an early detection of the channel state,
     * before handling the connection over to the HTTP stack.
     * It helps minimizing race conditions where the selector manager
     * thread hasn't woken up - or hasn't raised the event, before
     * the connection was retrieved from the pool. It helps reduce
     * the occurrence of "HTTP/1.1 parser received no bytes"
     * exception, when the server closes the connection while
     * it's being taken out of the pool.
     * <p>
     * This method attempts to read one byte from the underlying
     * channel. Because the connection was in the pool - there
     * should be nothing to read.
     * <p>
     * If {@code read} manages to read a byte off the connection, this is a
     * protocol error: the method closes the connection and returns false.
     * If {@code read} returns EOF, the method closes the connection and
     * returns false.
     * If {@code read} throws an exception, the method returns false.
     * Otherwise, {@code read} returns 0, the channel appears to be
     * still open, and the method returns true.
     * @return true if the channel appears to be still open.
     */
    final boolean checkOpen() {
        if (isOpen()) {
            try {
                // channel is non blocking
                int read = channel().read(ByteBuffer.allocate(1));
                if (read == 0) return true;
                close();
            } catch (IOException x) {
                debug.log("Pooled connection is no longer operational: %s",
                        x.toString());
                return false;
            }
        }
        return false;
    }
void closeOrReturnToCache(HttpHeaders hdrs) {
        if (hdrs == null) {
            // the connection was closed by server, eof
            Log.logTrace("Cannot return connection to pool: closing {0}", this);
            close();
            return;
        }
        HttpClientImpl client = client();
        if (client == null) {
            Log.logTrace("Client released: closing {0}", this);
            close();
            return;
        }
        ConnectionPool pool = client.connectionPool();
        boolean keepAlive = hdrs.firstValue("Connection")
                .map((s) -> !s.equalsIgnoreCase("close"))
                .orElse(true);
        if (keepAlive && checkOpen()) {
            Log.logTrace("Returning connection to the pool: {0}", this);
            pool.returnToPool(this);
        } else {
            Log.logTrace("Closing connection (keepAlive={0}, isOpen={1}): {2}",
                    keepAlive, isOpen(), this);
            close();
        }
    }

以上就是java.net.http.HttpClient使用示例解析的详细内容,更多关于java.net.http.HttpClient的资料请关注脚本之家其它相关文章!

相关文章

  • Java实现权重随机算法详解

    Java实现权重随机算法详解

    平时,经常会遇到权重随机算法,从不同权重的N个元素中随机选择一个,并使得总体选择结果是按照权重分布的。本文就详细来介绍如何实现,感兴趣的可以了解一下
    2021-07-07
  • SpringBoot集成Spring Security的方法

    SpringBoot集成Spring Security的方法

    Spring security,是一个强大的和高度可定制的身份验证和访问控制框架。这篇文章主要介绍了SpringBoot集成Spring Security的操作方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-07-07
  • 浅谈为什么同一个java文件只能有一个public类

    浅谈为什么同一个java文件只能有一个public类

    这篇文章主要介绍了浅谈为什么同一个java文件只能有一个public类,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • jdk15的安装与配置全过程记录

    jdk15的安装与配置全过程记录

    这篇文章主要给大家介绍了关于jdk15的安装与配置,文中通过图文介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • java AES加密/解密实现完整代码(附带源码)

    java AES加密/解密实现完整代码(附带源码)

    这篇文章主要介绍了java AES加密/解密实现的相关资料,包括AES加密算法的基本原理、Java加密API的使用方法以及项目实现的步骤和代码示例,需要的朋友可以参考下
    2025-04-04
  • SpringBoot打印详细启动异常信息

    SpringBoot打印详细启动异常信息

    这篇文章主要介绍了SpringBoot打印详细启动异常信息,本文包含了详细的过程解析与案例,概要的说明了如何去使用打印启动异常信息,需要的朋友可以参考下
    2021-06-06
  • java线程池对象ThreadPoolExecutor的深入讲解

    java线程池对象ThreadPoolExecutor的深入讲解

    在我们的开发中“池”的概念并不罕见,有数据库连接池、线程池、对象池、常量池等等。下面这篇文章主要给大家介绍了关于java线程池对象ThreadPoolExecutor的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧
    2018-09-09
  • 一文盘点Java中常见内存泄漏场景与解决方法

    一文盘点Java中常见内存泄漏场景与解决方法

    内存泄漏 是指对象 已经不再被程序使用,但因为某些原因 无法被垃圾回收器回收,长期占用内存,最终可能引发 OOM,本文会介绍常见的几类内存泄漏场景,大家可以避免一下
    2025-12-12
  • 在maven中引入本地jar包的步骤

    在maven中引入本地jar包的步骤

    这篇文章主要介绍了在maven中引入本地jar包的步骤,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下
    2021-04-04
  • Spring Cloud Alibaba 本地调试介绍及方案设计

    Spring Cloud Alibaba 本地调试介绍及方案设计

    为了解决 本地调试 的问题,本文实现了一种简单实用的策略,可以通过 Nacos 动态配置服务路由,还可以基于用户,部门,组织等级别配置服务路由,实现 本地调试 的同时,实际上也实现 灰度发布,感兴趣的朋友跟随小编一起看看吧
    2021-07-07

最新评论