Java - 检查打开的URL连接并获取IP地址

时间:2017-11-22 17:58:57

标签: java dns connection recaptcha

我们在Java应用程序中连接到Google for ReCaptcha时出现零星的连接超时问题。我知道关于SO的这个一般性问题还有其他问题,但我的问题略有不同。我想知道是否有办法检查我们已打开的URLConnection,以确定它实际尝试连接的IP地址。我们怀疑防火墙/ DNS问题的某些组合,但我们真正想做的是记录实际为主机解析的IP地址,以便我们收到任何超时。

1 个答案:

答案 0 :(得分:0)

在最简单的情况下,您可以在URL中对主机名执行DNS查找:

String hostname = urlConnection.getURL().getHost();
String ipAddress = InetAddress.getByName(hostname).getHostAddress();

如果您需要知道HTTP重定向可能带来的所有IP地址,您需要致电setInstanceFollowRedirects(false)并自行处理:

HttpURLConnection httpConn = (HttpURLConnection) urlConnection;
httpConn.setInstanceFollowRedirects(false);

while (true) {
    String hostname = urlConnection.getURL().getHost();
    String ipAddress = InetAddress.getByName(hostname).getHostAddress();

    System.out.printf("%s resolves to %s%n", hostname, ipAddress);

    if (httpConn.getResponseCode() / 100 != 3) {
        break;
    }

    String newURL = httpConn.getHeaderField("Location");
    if (newURL == null) {
        break;
    }

    urlConnection = new URL(newURL).openConnection();

    httpConn = (HttpURLConnection) urlConnection;
    httpConn.setInstanceFollowRedirects(false);
}
相关问题