我读过这个:
http://httpcomponents.10934.n7.nabble.com/get-InetAddress-for-the-HTTP-TARGET-HOST-td18332.html
我无法弄清楚如何使用最新的Apache HttpClient 4.3.3做同样的事情。 我想要做的是获取所请求站点的IP。我知道这对于最小的httpclient是不可能的,但它究竟应该如何使用?
由于最小的httpclient将PoolingHttpClientConnectionManager(HttpClientConnectionManager)作为参数而不是ClientConnectionManager,因此我不知道要覆盖哪些方法以及要设置哪些属性。 上面的示例可以直接访问套接字,而新的套接字则不然。
所以问题是如何使用新的(4.3.3)API做到这一点。 以及如何将已经解析的IP保留在重定向中是正确的,例如避免 第二个DNS解析。
一个代码片段,它近似于链接中写入的内容,并且两行输出都是NULL:
public static void main(String[] args) throws ClientProtocolException,
IOException {
String s = "http://google.com";
PoolingHttpClientConnectionManager m = new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", new PlainConnectionSocketFactory() {
@Override
public Socket createSocket(HttpContext context)
throws IOException {
Socket s = super.createSocket(context);
context.setAttribute("sock-address",
s.getRemoteSocketAddress());
return s;
}
}).build(), new SystemDefaultDnsResolver());
CloseableHttpClient minimal = HttpClients.createMinimal(m);
HttpGet get = new HttpGet(s);
HttpClientContext context = HttpClientContext.create();
CloseableHttpResponse response = minimal.execute(get, context);
InetSocketAddress addr = (InetSocketAddress) context
.getAttribute("sock-address");
HttpHost target = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
System.out.println(addr);
System.out.println(target.getAddress());
}
唯一的maven依赖项:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.3</version>
</dependency>