我得到這個錯誤爲這個特定的網站(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());
}
}
謝謝,這是有道理的,有沒有辦法檢測到有一個默認頁面,並下載該頁面? – code511788465541441
我相信你可以使用'http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#getErrorStream()'獲取返回的數據,即使2xx代碼不是回。檢查響應代碼('getResponseCode')並根據狀態使用正確的流方法。 – Pedantic