Java:在一个方法里url.openConnection()联网,IP地址不存在时http状态码都拿不到就抛异常了肿么办?
publicstaticInputStreamgetHttpStream(finalStringurlPath)throwsIOException{URLurl=newU...
public static InputStream getHttpStream(final String urlPath) throws IOException{
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
System.err.println("返回的http状态码是:"+conn.getResponseCode());
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
return conn.getInputStream();
}
return null;
}
报错是:java.net.SocketException: failed to connect to /192.168.1.100 (port 8080) after 5000ms: isConnected failed: EHOSTUNREACH (No route to host)
想要的结果是就算IP不存在也拿到状态码 展开
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
System.err.println("返回的http状态码是:"+conn.getResponseCode());
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
return conn.getInputStream();
}
return null;
}
报错是:java.net.SocketException: failed to connect to /192.168.1.100 (port 8080) after 5000ms: isConnected failed: EHOSTUNREACH (No route to host)
想要的结果是就算IP不存在也拿到状态码 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询