为什么即使url工作正常,此代码也会抛出java.io.FileNotFoundException

时间:2014-01-29 21:25:17

标签: java http

我收到此特定网站的错误(nandos.co.uk/southharrow)。其他网址工作正常。谁知道为什么?

  

java.io.FileNotFoundException:http://www.nandos.co.uk/southharrow at   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());
    }

}

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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

您应该再次验证网址路径。此外,您可能希望尝试使用curl进行快速测试。