有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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);
        }
    }

共 (2) 个答案

  1. # 1 楼答案

    https://instagram.com/p/2cZgLGSdIe/实际返回404未找到

    $ curl -I https://instagram.com/p/2cZgLGSdIe/
    HTTP/1.1 404 NOT FOUND
    

    所以我猜FileNotFoundException是预期的行为

  2. # 2 楼答案

    通过使用HttpURLConnectiongetResponseCode()检查页面是否有效,返回200或页面未找到404,未经授权401修复了该问题

                URL url = new URL("https://instagram.com/p/2cZgLGSdIe/");
                  HttpURLConnection con = (HttpURLConnection) url
                    .openConnection();
                  if(con.getResponseCode() == 200){
                      System.out.println("Page is ok!");
                  }
                  else{
                  System.out.println("Page not found 404 /unauthorized 401 ");
                  }