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的资料请关注脚本之家其它相关文章!

相关文章

  • Mock和@InjectMocks的区别及说明

    Mock和@InjectMocks的区别及说明

    @Mock和@InjectMocks是Mockito框架中的两个注解,前者用于创建模拟对象,后者用于将模拟对象注入到被测试类中
    2024-11-11
  • java普通项目读取不到resources目录下资源文件的解决办法

    java普通项目读取不到resources目录下资源文件的解决办法

    这篇文章主要给大家介绍了关于java普通项目读取不到resources目录下资源文件的解决办法,Web项目中应该经常有这样的需求,在maven项目的resources目录下放一些文件,比如一些配置文件,资源文件等,需要的朋友可以参考下
    2023-09-09
  • 实例详解Java中如何对方法进行调用

    实例详解Java中如何对方法进行调用

    这篇文章主要介绍了实例详解Java中如何对方法进行调用,是Java入门学习中的基础知识,需要的朋友可以参考下
    2015-10-10
  • Java 使用线程池执行多个任务的示例

    Java 使用线程池执行多个任务的示例

    这篇文章主要介绍了Java 使用线程池执行多个任务的示例,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下
    2021-03-03
  • 在 Spring Boot 项目中实现文件下载功能

    在 Spring Boot 项目中实现文件下载功能

    这篇文章主要介绍了在 Spring Boot 项目中实现文件下载功能,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-09-09
  • springboot整合freemarker的踩坑及解决

    springboot整合freemarker的踩坑及解决

    这篇文章主要介绍了springboot整合freemarker的踩坑及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • 三道java新手入门面试题,通往自由的道路--多线程

    三道java新手入门面试题,通往自由的道路--多线程

    这篇文章主要为大家分享了最有价值的3道多线程面试题,涵盖内容全面,包括数据结构和算法相关的题目、经典面试编程题等,对hashCode方法的设计、垃圾收集的堆和代进行剖析,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • Java实现螺旋矩阵的示例

    Java实现螺旋矩阵的示例

    这篇文章主要介绍了Java实现螺旋矩阵的示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-02-02
  • Python中scrapy框架的ltem和scrapy.Request详解

    Python中scrapy框架的ltem和scrapy.Request详解

    这篇文章主要介绍了Python中scrapy框架的ltem和scrapy.Request详解,Item是保存爬取数据的容器,它的使用方法和字典类似,不过,相比字典,Item提供了额外的保护机制,可以避免拼写错误或者定义字段错误,需要的朋友可以参考下
    2023-09-09
  • Java归并排序算法代码实现

    Java归并排序算法代码实现

    归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的,下面这篇文章主要给大家介绍了关于Java归并排序算法的相关资料,需要的朋友可以参考下
    2024-03-03

最新评论