HttpURLConnection上的java FileNotFoundException。getInputStream
我在下面的代码中得到了这个错误,openStream()的错误原因我相信,我只是想得到下面URL页面的内容,如果我将instagram页面的URL更改为其他内容,代码效果会很好,但如果我将其保留在以下URL中,而该URL在Instagram页面中找不到页面,则会导致此错误
Exception in thread "main" java.io.FileNotFoundException: https://instagram.com/p/2cZgLGSdIe/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1624)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at java.net.URL.openStream(URL.java:1037)
at getURLfinal.getURL.main(getURL.java:17)
守则:
public class getURL {
public static void main(String[] args) throws MalformedURLException, IOException {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
String url = "";
String out = new Scanner(new URL("https://instagram.com/p/2cZgLGSdIe/").openStream(), "UTF-8").useDelimiter("\\A").next();
System.out.println(out);
}
}
# 1 楼答案
https://instagram.com/p/2cZgLGSdIe/实际返回404未找到
所以我猜
FileNotFoundException
是预期的行为# 2 楼答案
通过使用
HttpURLConnection
和getResponseCode()
检查页面是否有效,返回200
或页面未找到404
,未经授权401
修复了该问题