I was able to solve this problem using Apache Commons HttpClient , see below code snippet.
As I was afraid, the URLConnection provided by java.net is a very simplified implementation and will try to use only the first IP address from the allowed list. If you really are not allowed to use another library, you will have to write your own error handling. This is useless since you will need to resolve all IP addresses before using InetAddress and connect to each IP address by passing the "Host: domain.name" header to the HTTP stack directly until one of the IP addresses answers.
The Apache library is significantly more reliable and allows you to configure most. You can control how many times it will try again, and, most importantly, it will automatically try to resolve all IP addresses with the same name until one of them answers successfully.
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();
Hope this helps!
source share