httpclient connect连接请求方法源码解读

 更新时间:2023年11月26日 11:52:43   作者:codecraft  
这篇文章主要为大家介绍了httpclient connect连接请求方法解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

序

本文主要研究一下httpclient的connect

HttpClientConnectionOperator

org/apache/http/conn/HttpClientConnectionOperator.java

public interface HttpClientConnectionOperator {

    void connect(
            ManagedHttpClientConnection conn,
            HttpHost host,
            InetSocketAddress localAddress,
            int connectTimeout,
            SocketConfig socketConfig,
            HttpContext context) throws IOException;

    void upgrade(
            ManagedHttpClientConnection conn,
            HttpHost host,
            HttpContext context) throws IOException;

}
HttpClientConnectionOperator定义了connect及upgrade方法,它有一个默认的实现类为DefaultHttpClientConnectionOperator

DefaultHttpClientConnectionOperator

org/apache/http/impl/conn/DefaultHttpClientConnectionOperator.java

public class DefaultHttpClientConnectionOperator implements HttpClientConnectionOperator {
    static final String SOCKET_FACTORY_REGISTRY = "http.socket-factory-registry";
    private final Log log = LogFactory.getLog(getClass());
    private final Lookup<ConnectionSocketFactory> socketFactoryRegistry;
    private final SchemePortResolver schemePortResolver;
    private final DnsResolver dnsResolver;
    public DefaultHttpClientConnectionOperator(
            final Lookup<ConnectionSocketFactory> socketFactoryRegistry,
            final SchemePortResolver schemePortResolver,
            final DnsResolver dnsResolver) {
        super();
        Args.notNull(socketFactoryRegistry, "Socket factory registry");
        this.socketFactoryRegistry = socketFactoryRegistry;
        this.schemePortResolver = schemePortResolver != null ? schemePortResolver :
            DefaultSchemePortResolver.INSTANCE;
        this.dnsResolver = dnsResolver != null ? dnsResolver :
            SystemDefaultDnsResolver.INSTANCE;
    }
    //......
    public void connect(
            final ManagedHttpClientConnection conn,
            final HttpHost host,
            final InetSocketAddress localAddress,
            final int connectTimeout,
            final SocketConfig socketConfig,
            final HttpContext context) throws IOException {
        final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
        final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
        if (sf == null) {
            throw new UnsupportedSchemeException(host.getSchemeName() +
                    " protocol is not supported");
        }
        final InetAddress[] addresses = host.getAddress() != null ?
                new InetAddress[] { host.getAddress() } : this.dnsResolver.resolve(host.getHostName());
        final int port = this.schemePortResolver.resolve(host);
        for (int i = 0; i < addresses.length; i++) {
            final InetAddress address = addresses[i];
            final boolean last = i == addresses.length - 1;
            Socket sock = sf.createSocket(context);
            sock.setSoTimeout(socketConfig.getSoTimeout());
            sock.setReuseAddress(socketConfig.isSoReuseAddress());
            sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
            sock.setKeepAlive(socketConfig.isSoKeepAlive());
            if (socketConfig.getRcvBufSize() > 0) {
                sock.setReceiveBufferSize(socketConfig.getRcvBufSize());
            }
            if (socketConfig.getSndBufSize() > 0) {
                sock.setSendBufferSize(socketConfig.getSndBufSize());
            }
            final int linger = socketConfig.getSoLinger();
            if (linger >= 0) {
                sock.setSoLinger(true, linger);
            }
            conn.bind(sock);
            final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
            if (this.log.isDebugEnabled()) {
                this.log.debug("Connecting to " + remoteAddress);
            }
            try {
                sock = sf.connectSocket(
                        connectTimeout, sock, host, remoteAddress, localAddress, context);
                conn.bind(sock);
                if (this.log.isDebugEnabled()) {
                    this.log.debug("Connection established " + conn);
                }
                return;
            } catch (final SocketTimeoutException ex) {
                if (last) {
                    throw new ConnectTimeoutException(ex, host, addresses);
                }
            } catch (final ConnectException ex) {
                if (last) {
                    final String msg = ex.getMessage();
                    throw "Connection timed out".equals(msg)
                                    ? new ConnectTimeoutException(ex, host, addresses)
                                    : new HttpHostConnectException(ex, host, addresses);
                }
            } catch (final NoRouteToHostException ex) {
                if (last) {
                    throw ex;
                }
            }
            if (this.log.isDebugEnabled()) {
                this.log.debug("Connect to " + remoteAddress + " timed out. " +
                        "Connection will be retried using another IP address");
            }
        }
    }
}
DefaultHttpClientConnectionOperator的connect先通过getSocketFactoryRegistry获取Lookup<ConnectionSocketFactory>,再通过它获取ConnectionSocketFactory,之后通过dnsResolver解析地址,再通过schemePortResolver解析port,然后通过ConnectionSocketFactory创建socket,并根据socketConfig设置socket的参数,最后执行connectSocket,并绑定到conn

connectSocket

org/apache/http/conn/socket/PlainConnectionSocketFactory.java

public class PlainConnectionSocketFactory implements ConnectionSocketFactory {

    public static final PlainConnectionSocketFactory INSTANCE = new PlainConnectionSocketFactory();

    public static PlainConnectionSocketFactory getSocketFactory() {
        return INSTANCE;
    }

    public PlainConnectionSocketFactory() {
        super();
    }

    @Override
    public Socket createSocket(final HttpContext context) throws IOException {
        return new Socket();
    }

    @Override
    public Socket connectSocket(
            final int connectTimeout,
            final Socket socket,
            final HttpHost host,
            final InetSocketAddress remoteAddress,
            final InetSocketAddress localAddress,
            final HttpContext context) throws IOException {
        final Socket sock = socket != null ? socket : createSocket(context);
        if (localAddress != null) {
            sock.bind(localAddress);
        }
        try {
            sock.connect(remoteAddress, connectTimeout);
        } catch (final IOException ex) {
            try {
                sock.close();
            } catch (final IOException ignore) {
            }
            throw ex;
        }
        return sock;
    }

}
PlainConnectionSocketFactory的createSocket直接new一个socket,其connectSocket方法则执行sock.connect

socketConfig

resolveSocketConfig

org/apache/http/impl/conn/PoolingHttpClientConnectionManager.java

private SocketConfig resolveSocketConfig(final HttpHost host) {
        SocketConfig socketConfig = this.configData.getSocketConfig(host);
        if (socketConfig == null) {
            socketConfig = this.configData.getDefaultSocketConfig();
        }
        if (socketConfig == null) {
            socketConfig = SocketConfig.DEFAULT;
        }
        return socketConfig;
    }
PoolingHttpClientConnectionManager的resolveSocketConfig先是从configData根据指定host获取socketConfig,若为null则再从configData获取默认的socketConfig,若为null则返回默认的socketConfig

setSocketConfig

org/apache/http/impl/conn/PoolingHttpClientConnectionManager.java

public void setDefaultSocketConfig(final SocketConfig defaultSocketConfig) {
        this.configData.setDefaultSocketConfig(defaultSocketConfig);
    }

    public void setSocketConfig(final HttpHost host, final SocketConfig socketConfig) {
        this.configData.setSocketConfig(host, socketConfig);
    }
PoolingHttpClientConnectionManager提供了setDefaultSocketConfig、setSocketConfig方法

SocketConfig.DEFAULT

org/apache/http/config/SocketConfig.java

public class SocketConfig implements Cloneable {

    public static final SocketConfig DEFAULT = new Builder().build();

    //......

    public static class Builder {

        private int soTimeout;
        private boolean soReuseAddress;
        private int soLinger;
        private boolean soKeepAlive;
        private boolean tcpNoDelay;
        private int sndBufSize;
        private int rcvBufSize;
        private int backlogSize;

        Builder() {
            this.soLinger = -1;
            this.tcpNoDelay = true;
        }

        //......
    }
}
默认的socketConfig,除了tcpNoDelay为true,其他的都为false,然后soLinger为-1

小结

HttpClientConnectionOperator定义了connect及upgrade方法,它有一个默认的实现类为DefaultHttpClientConnectionOperator;DefaultHttpClientConnectionOperator的connect先通过getSocketFactoryRegistry获取Lookup<ConnectionSocketFactory>,再通过它获取ConnectionSocketFactory,之后通过dnsResolver解析地址,再通过schemePortResolver解析port,然后通过ConnectionSocketFactory创建socket,并根据socketConfig设置socket的参数,最后执行connectSocket,并绑定到conn;默认的socketConfig,除了tcpNoDelay为true,其他的都为false,然后soLinger为-1。

以上就是httpclient connect连接请求方法源码解读的详细内容,更多关于httpclient connect连接请求的资料请关注脚本之家其它相关文章!

相关文章

  • 详解Java深拷贝,浅拷贝和Cloneable接口

    详解Java深拷贝,浅拷贝和Cloneable接口

    这篇文章主要为大家详细介绍了Java中Cloneable接口以及深拷贝与浅拷贝的相关知识,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-08-08
  • 重新认识Java中的ThreadLocal

    重新认识Java中的ThreadLocal

    ThreadLocal是JDK包提供的,它提供线程本地变量,如果创建一个ThreadLocal变量,那么访问这个变量的每个线程都会有这个变量的一个副本,在实际多线程操作的时候,操作的是自己本地内存中的变量,从而规避了线程安全问题
    2021-05-05
  • spring声明式事务管理解析

    spring声明式事务管理解析

    这篇文章主要为大家详细介绍了spring声明式事务管理,对spring事务管理进行深入了解,感兴趣的小伙伴们可以参考一下
    2016-10-10
  • Java中IO流概述

    Java中IO流概述

    大家好,本篇文章主要讲的是Java中IO流概述,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下,方便下次浏览
    2022-01-01
  • spring 重复注解和aop拦截的实现示例

    spring 重复注解和aop拦截的实现示例

    本文主要介绍了spring 重复注解和aop拦截的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-08-08
  • 解读Spring配置文件中的property标签中的属性

    解读Spring配置文件中的property标签中的属性

    这篇文章主要介绍了Spring配置文件中的property标签中的属性,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-01-01
  • Java写入写出Excel操作源码分享

    Java写入写出Excel操作源码分享

    这篇文章主要介绍了Java写入写出Excel操作源码分享,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • JAVA实现生成短链接的示例代码

    JAVA实现生成短链接的示例代码

    短链接就是将长度较长的链接压缩成较短的链接,本文就来介绍一下JAVA实现生成短链接的示例代码,具有一定的参考价值,感兴趣的可以了解一下
    2023-08-08
  • Spring中过滤器(Filter)和拦截器(Interceptor)到底啥区别详解

    Spring中过滤器(Filter)和拦截器(Interceptor)到底啥区别详解

    在Spring框架中过滤器(Filter)和拦截器(Interceptor)都是用于处理HTTP请求的重要组件,但它们的工作原理和执行顺序有所不同,这篇文章主要介绍了Spring中过滤器(Filter)和拦截器(Interceptor)到底啥区别的相关资料,需要的朋友可以参考下
    2026-04-04
  • springboot打包不同环境配置以及shell脚本部署的方法

    springboot打包不同环境配置以及shell脚本部署的方法

    这篇文章主要给大家介绍了关于springboot打包不同环境配置以及shell脚本部署的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者使用springboot具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-03-03

最新评论