2014-01-29 34 views
0

我得到這個錯誤爲這個特定的網站(nandos.co.uk/southharrow)。其他網址工作正常。有人知道爲什麼爲什麼這段代碼拋出一個java.io.FileNotFoundException,即使URL工作正常

java.io.FileNotFoundException:http://www.nandos.co.uk/southharrow在 sun.net.www.protocol.http.HttpURLConnection.getInputStream(未知 來源)

public class Test { 
    public static void main(String[] args) { 
     HttpURLConnection conn = null; 
     StringBuilder result = new StringBuilder(); 
     try { 
      String website = "http://www.nandos.co.uk/southharrow"; 
      URL url = new URL(website.trim()); 
      conn = (HttpURLConnection) url.openConnection(); 
      InputStreamReader in = new InputStreamReader(conn.getInputStream()); 

      int read; 
      char[] buff = new char[1024]; 
      while ((read = in.read(buff)) != -1) { 
       result.append(buff, 0, read); 
      } 
     } catch (MalformedURLException e) { 
      System.out.println("Error processing Places API URL"); 
      e.printStackTrace(); 
     } catch (IOException e) { 
      System.out.println("Error connecting to Places API"); 
      e.printStackTrace(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      if (conn != null) { 
       conn.disconnect(); 
      } 

     } 
     System.out.println(result.toString()); 
    } 

} 

回答

4
$ wget http://www.nandos.co.uk/southharrow 
--2014-01-29 16:28:31-- http://www.nandos.co.uk/southharrow 
Resolving www.nandos.co.uk... 162.13.100.232 
Connecting to www.nandos.co.uk|162.13.100.232|:80... connected. 
HTTP request sent, awaiting response... 404 Not Found 
2014-01-29 16:28:31 ERROR 404: Not Found. 

沒有URL存在於該地址。您看到的頁面是出現錯誤時顯示的默認頁面。類似於「FileNotFoundException異常」

+0

謝謝,這是有道理的,有沒有辦法檢測到有一個默認頁面,並下載該頁面? – code511788465541441

+0

我相信你可以使用'http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#getErrorStream()'獲取返回的數據,即使2xx代碼不是回。檢查響應代碼('getResponseCode')並根據狀態使用正確的流方法。 – Pedantic

1

看來,URL是不正確並返回404,這被解釋爲一個FileNotFoundException異常:

> GET /southharrow HTTP/1.1 
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8y zlib/1.2.5 
> Host: www.nandos.co.uk 
> Accept: */* 
> 
< HTTP/1.1 404 Not Found 
< Date: Wed, 29 Jan 2014 21:28:59 GMT 
< Server: Apache 
< X-Powered-By: PHP/5.3.27 

你應該再次驗證URL路徑。此外,您可能想嘗試使用curl進行快速測試。

相關問題