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,即使主机信誉良好(如其他方法所示)。
答案 0 :(得分:4)
<强> 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库