-1

如何让我的程序返回 MalformedUrlException 而不仅仅是通用异常?

我正在制作一个简单的函数,它读取用户在控制台中输入的 URL,并从 URL 返回内容。我需要它来检查 URL 是有效的 URL 还是不是有效的 URL。

示例网址: http://google.com/not-found.html http://google.com

我创建了两个捕获异常,但似乎总是返回整体异常而不是 MalformedUrlException。

    public static String getUrlContents(String theUrl) {
    String content = "";
    try {
        URL url = new URL(theUrl);
        //Create a url connection object 
        URLConnection urlConnection = url.openConnection();
        //wrap the url connection a buffered reader 
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line;
        while((line = bufferedReader.readLine()) != null) {
            content += line + "\n";
        }
        bufferedReader.close();
    } catch (MalformedURLException e) {
        System.out.println("The following url is invalid'" + theUrl + "'");
        //logging error should go here
    } catch (Exception e) {
        System.out.println("Something went wrong, try agian");
    }
    return content;
}
4

1 回答 1

0

首先,java.net.MalformedURLException 不是“未找到”资源的情况:

公共类 MalformedURLException 扩展 IOException

抛出表示出现了格式错误的 URL。在规范字符串中找不到合法协议,或者无法解析该字符串。

我了解到您希望了解 URL 导致未找到返回码 (404) 的情况。为此,您需要检查 HTTP 响应代码。

最简单的方法是使用java.net.HttpURLConnection

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/net/HttpURLConnection.html

公共抽象类 HttpURLConnection 扩展了 URLConnection

支持 HTTP 特定功能的 URLConnection。有关详细信息,请参阅规范。

每个 HttpURLConnection 实例用于发出单个请求,但到 HTTP 服务器的底层网络连接可能会被其他实例透明地共享。在请求之后对 HttpURLConnection 的 InputStream 或 OutputStream 调用 close() 方法可能会释放与此实例关联的网络资源,但不会影响任何共享的持久连接。如果持续连接当时处于空闲状态,则调用 disconnect() 方法可能会关闭底层套接字。

您可以通过调用来检查响应代码getResponseCode()。如果结果小于 400,则您得到有效响应,否则为客户端错误 (4xx) 或服务器错误 (5xx)。

像这样的东西:

public static String getUrlContents(String theUrl) {
    String content = "";
    try {
        URL url = new URL(theUrl);
        //Create a url connection object 
        URLConnection urlConnection = url.openConnection();
        if (urlConnection instanceof HttpURLConnection) {
            HttpURLConnection conn = (HttpURLConnection) urlConnection;
            if (conn.getResponseCode() < 400) {
                // read contents
            } else {
                System.out.println(conn.getResponseMessage());
                // treat the error as you like
            }
        } else {
            // not a HTTP connection, treat as you like
        }
    } catch (MalformedURLException e) {
        System.out.println("The following url is invalid'" + theUrl + "'");
        //logging error should go here
    } catch (Exception e) {
        System.out.println("Something went wrong, try agian");
    }
    return content;
}

我没有检查代码,但我认为你可以得到整体的想法。

于 2019-03-24T13:52:14.147 回答