boolean reachable = false;

while (true){
    Socket socket = null;
    while (reachable == false && (System.currentTimeMillis() < (CUR_TIME + 1000))){
        try {
            socket = new Socket(hostname, 80);
            reachable = true;
        } catch ( UnknownHostException e) {
            reachable = false;
        }
    }
}

我想最终调用status = httpConnection.getResponseCode();,但是如果用户输入了无法访问的主机,则会出现错误。因此,我使用上面的代码来确保主机可用。但是,即使主机保持良好状态,reachable始终返回false(如其他方法所示)。

最佳答案

HttpURLConnection :

try{
    URL url = new URL("http://tes23123t.com");
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setRequestMethod("GET");
    connection.connect();
    int respCode = connection.getResponseCode();
    System.out.println(respCode);
}catch(UnknownHostException e){
    System.out.println("Unknown Host!!");
}

或者,如果您希望更简单的实现,则可以使用OKHttp库

10-08 09:15