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;
}
}
}
I want to eventually call status = httpConnection.getResponseCode();
, but if the user inputs an unreachable host, there is an error. Therefore, I'm using the above code to make sure the host is available. However, reachable
always returns as false, even if the host is in good standing (as shown by other methods).
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!!");
}
Or you could use OKHttp library if you prefer easier implementation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.