在这里设置了setConnectTimeout和setReadTimeout。但好像没起作用,有了解的可以共享一下。
public static void main(String[] args) {
// start
try {
HttpURLConnection httpUrlConn = (HttpURLConnection) new URL(
"http://www.baidu.com").openConnection();
// 设置连接主机超时(单位:毫秒)
httpUrlConn.setConnectTimeout(200);
// 设置从主机读取数据超时(单位:毫秒)
httpUrlConn.setReadTimeout(200);
System.out.println(new Date());
int statusCode = httpUrlConn.getResponseCode();
System.out.println(new Date());
System.out.println(statusCode);
if (statusCode != 200) {
System.out.println("不存在");
} else {
System.out.println("可以访问");
}
// 打开流关闭
InputStream is2 = httpUrlConn.getInputStream();
is2.close();
} catch (Exception e) {
System.out.println("error:" + new Date());
// TODO: handle exception
System.err.println(e.getMessage());
}
// end
}