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实现Excel转换为图片

    java实现Excel转换为图片

    在实际开发过程中,经常会有这样的需求,需要将Excel表格或特定区域转换为图片,所以小编今天就来为大家介绍一下如何使用Java将Excel转化为图片吧
    2023-10-10
  • 亲测SpringBoot参数传递及@RequestBody注解---踩过的坑及解决

    亲测SpringBoot参数传递及@RequestBody注解---踩过的坑及解决

    这篇文章主要介绍了亲测SpringBoot参数传递及@RequestBody注解---踩过的坑及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • SpringBoot整合junit与Mybatis流程详解

    SpringBoot整合junit与Mybatis流程详解

    这篇文章主要介绍了SpringBoot整合第三方技术,包括整合Junit、整合Mybatis,本文通过实例代码相结合给大家介绍的非常详细,需要的朋友可以参考下
    2022-08-08
  • 简单易懂讲解happens-before原则

    简单易懂讲解happens-before原则

    Java内存模型中的happens-before是什么?为什么会有这东西的存在?一个新东西肯定是上手先,但是等我们空下来回过头来,我们还是需要去理解这些知识,只有这样我才能深刻的记住,并且运用熟练。下来和小编来一起学习下
    2019-05-05
  • struts2中实现多个文件同时上传代码

    struts2中实现多个文件同时上传代码

    struts2中实现多个文件同时上传代码,需要的朋友可以参考一下
    2013-04-04
  • Mybatis无法获取带有下划线前缀的字段的值问题

    Mybatis无法获取带有下划线前缀的字段的值问题

    这篇文章主要介绍了Mybatis无法获取带有下划线前缀的字段的值问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • Mybatis执行流程、缓存原理及相关面试题汇总

    Mybatis执行流程、缓存原理及相关面试题汇总

    最近刚学完MyBatis,趁着大好机会,总结一下它的执行流程,面试也爱问这个,下面这篇文章主要给大家介绍了关于Mybatis执行流程、缓存原理及相关面试题的相关资料,需要的朋友可以参考下
    2022-02-02
  • Java简单使用EasyExcel操作读写excel的步骤与要点

    Java简单使用EasyExcel操作读写excel的步骤与要点

    相信现在很多搞后端的同学大部分做的都是后台管理系统,那么管理系统就肯定免不了Excel的导出导入功能,下面这篇文章主要给大家介绍了关于Java简单使用EasyExcel操作读写excel的步骤与要点,需要的朋友可以参考下
    2022-09-09
  • java8 stream的分组功能实例介绍

    java8 stream的分组功能实例介绍

    这篇文章主要给大家介绍了关于java8 stream的分组功能的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用java8具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-12-12
  • 如何动态替换Spring容器中的Bean

    如何动态替换Spring容器中的Bean

    这篇文章主要介绍了如何动态替换Spring容器中的Bean,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-08-08

最新评论