Java 如何执行畸形异常/404找不到

Java 如何执行畸形异常/404找不到,java,http,exception,get,malformedurlexception,Java,Http,Exception,Get,Malformedurlexception,如何使我的程序返回MalformedUrlException而不仅仅是一般异常 我正在制作一个简单的函数,它读取用户在控制台中输入的URL,并从URL返回内容。我需要它来检查URL是否是有效的URL,或者它是否不是工作URL 示例URL: http://google.com 我创建了两个catch异常,但似乎总是返回整个异常,而不是MalformedUrlException public static String getUrlContents(String theUrl) {

如何使我的程序返回MalformedUrlException而不仅仅是一般异常

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

示例URL: http://google.com

我创建了两个catch异常,但似乎总是返回整个异常,而不是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;
}

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

公共类MalformedURLException扩展IOException

抛出以指示已发生格式错误的URL。要么没有法律依据 协议可以在规范字符串中找到,或者该字符串可以 无法解析

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

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

公共抽象类HttpURLConnection扩展了URLConnection

支持HTTP特定功能的URLConnection。请参见规范 详情请参阅

每个HttpURLConnection实例用于发出单个请求,但 与HTTP服务器的底层网络连接可能是 被其他实例透明地共享。调用close()方法 在HttpURLConnection的InputStream或OutputStream上 请求可能释放与此实例关联的网络资源,但 对任何共享的持久连接都没有影响。呼叫 断开连接()方法可能会关闭基础套接字,如果持久性 否则,此时连接处于空闲状态

您可以通过调用
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;
}
public静态字符串getUrlContents(字符串theUrl){
字符串内容=”;
试一试{
URL=新的URL(URL);
//创建url连接对象
URLConnection URLConnection=url.openConnection();
if(HttpURLConnection的urlConnection实例){
HttpURLConnection conn=(HttpURLConnection)urlConnection;
if(连接getResponseCode()<400){
//阅读内容
}否则{
System.out.println(conn.getResponseMessage());
//随意对待错误
}
}否则{
//不是HTTP连接,请随意处理
}
}捕获(格式错误){
System.out.println(“以下url无效'+theUrl+”);
//日志错误应该在这里出现
}捕获(例外e){
System.out.println(“出错了,再试一次”);
}
返回内容;
}

我还没有检查代码,但我认为您可以了解整体情况。

:Throws:MalformedURLException-如果没有指定协议,或者发现未知协议,或者规范为空。您能提供一个输入行为不受欢迎的示例吗?@tworogue,如果我输入http:/google.com,或者我希望它抛出一个错误MalformedURlException@AhmeeyaGoldman看看我的答案吧。