httpclient 发送http请求过程
2018-11-20 本文已影响0人
futureluck
socket建立示例
http请求是在应用层,建立在tcp/ip之上,httpclient的实现也是建立在socket操作上的,先看socket客户端发送消息示例:
// 1.建立端到端的连接
Socket socket = new Socket("127.0.0.1", 8080);
// 2.往输出流发送字节
OutputStream outputStream = socket.getOutputStream();
outputStream.write(1);
// 3.往输入流读取字节
InputStream inputStream = socket.getInputStream();
inputStream.read();
httpclient建立连接
httpclient就是把上述示例封装,先实例化PoolingHttpClientConnectionManager 构造函数默认传入DefaultHttpClientConnectionOperator实例,然后每次执行发送请求,先执行连接过程。
// 1.dns解析
// 2.解析端口,ip 建立连接
// 3.将建立的连接的socket对象赋值给conn对象
// 4.conn对象write数据,其实操作的就是socket的outputStream 对象
// 5.conn对象读取数据,其实操作的就是socket的inputStream对象
@Override
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());
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());
final int linger = socketConfig.getSoLinger();
if (linger >= 0) {
sock.setSoLinger(true, linger);
}
conn.bind(sock);
final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
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);
}
}
}
}