2011-09-19 156 views
6

我使用Java的HttpURLConnection类打foo.com有多个IP的Java HttpURLConnection的DNS解析地址

foo.com有多个A记录指向不同的IP地址(1.1.1.1 1.1.1.2和)

如果我的第一个连接呼叫解析为1.1.1.1,但那台机器停机,后续的连接呼叫会识别这个连接并尝试在1.1.1.2上连接吗?

或者我需要使用INetAddress API来实现这种逻辑吗?

+0

如果参数是一个url而不是ip,那么你不需要关心这个。 – Jacob

回答

6

我能够通过使用Apache Commons HttpClient解决此问题,请参阅下面的代码片段。

就像我担心的那样,java.net提供的URLConnection是一个非常简单的实现,它只会尝试解析列表中的第一个IP地址。如果你真的不被允许使用另一个库,你将不得不编写自己的错误处理。这很麻烦,因为您需要在使用InetAddress之前手动解析所有IP,并连接到通过“Host:domain.name”标头的每个IP,直到其中一个IP响应为止。

Apache库非常强大,并且可以进行大量的自定义。您可以控制重试次数,最重要的是,它会自动尝试解析为相同名称的所有IP地址,直到其中一个成功响应。

HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() { 
    @Override 
    public boolean retryRequest(IOException exception, int count, HttpContext context) { 
     try { 
      Thread.sleep(1000); 
     } catch (InterruptedException e) { 
     } 
     return count < 30; 
    } 
}; 

ConnectionKeepAliveStrategy keepAlive = new ConnectionKeepAliveStrategy() { 
    @Override 
    public long getKeepAliveDuration(HttpResponse response, HttpContext context) { 
     return 500; 
    } 
}; 

DefaultHttpClient httpclient = new DefaultHttpClient(); 
httpclient.getParams().setParameter("http.socket.timeout", new Integer(2000)); 
httpclient.getParams().setParameter("http.connection.timeout", new Integer(2000)); 
httpclient.setHttpRequestRetryHandler(myRetryHandler); 
httpclient.setKeepAliveStrategy(keepAlive); 
HttpGet httpget = new HttpGet("http://remotehost.com"); 
HttpResponse httpres = httpclient.execute(httpget); 
InputStream is = httpres.getEntity().getContent(); 

我希望这有助于!