HttpURLConnection.getInputStream中的FileNotFoundException

时间:2015-05-11 08:48:06

标签: java android

我为以下代码收到此错误,openStream()的错误原因我相信,我只想获取以下URL页面的内容,如果我更改URL,则代码效果很好将Instagram页面改为其他内容,但如果我将其保留到以下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 个答案:

答案 0 :(得分:1)

使用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 ");
              }

答案 1 :(得分:0)

https://instagram.com/p/2cZgLGSdIe/实际上会返回 404 NOT FOUND

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

所以我猜FileNotFoundException是预期的行为......