代理检查Java

时间:2014-11-19 09:56:40

标签: java url proxy connection

我尝试检查代理是否在线。但每次抛出异常。我也尝试使用System.setProperty(),但这也不起作用......

我的方法:

public static boolean isOnline(String host, int port)
{
    String url = "http://www.google.com";
    try
    {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(proxy);
        connection.connect();
        return true;

    } catch (Exception e)
    {
        return false;
    }
}

例外:

java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient$1.run(HttpClient.java:484)
at sun.net.www.http.HttpClient$1.run(HttpClient.java:482)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.http.HttpClient.privilegedOpenServer(HttpClient.java:481)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:522)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:211)
at sun.net.www.http.HttpClient.New(HttpClient.java:308)
at sun.net.www.http.HttpClient.New(HttpClient.java:326)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1167)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1146)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:997)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:931)
at viewer.ProxyCheck.isOnline(ProxyCheck.java:18)
at viewer.Viewer.main(Viewer.java:7)

谢谢你的时间!

1 个答案:

答案 0 :(得分:1)

试试这个:

public static boolean isOnline(){
    System.setProperty("http.proxyHost", "failProxyIP");
    System.setProperty("http.proxyPort", "failProxyPort");
    try {
        HttpURLConnection connection = (HttpURLConnection)new URL("http://www.google.com").openConnection();
        connection.connect();
        return true;
    } catch (Exception e) {
        return false;
    }
}

public static void main(String[] args) {
    System.out.println(isOnline()); //prints false
}