📜  java 从连接中读取,即使 404 - Java (1)

📅  最后修改于: 2023-12-03 14:42:17.722000             🧑  作者: Mango

Java 从连接中读取,即使 404

在 Java 中,我们经常需要从连接中读取数据。但有时我们可能会遇到 404 错误,这使得我们的程序无法正常读取数据。在本文中,我们将探讨如何从连接中读取数据,即使出现 404 错误。

使用 Java 的 URL 类读取连接

我们可以使用 Java 的 URL 类来读取连接。以下是一个样例程序:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class ReadFromURL {

    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

在这个样例程序中,我们使用了 Java 的 URL 类和 BufferedReader 类来读取连接中的数据。openStream 方法用于打开连接的输入流。

处理连接中的 404 错误

但有时我们可能会遇到连接中的 404 错误。如果直接执行上述程序,当连接中出现 404 错误时,我们的程序会抛出 FileNotFoundException 异常。

为了解决这个问题,我们需要检查连接中的响应码,如果响应码为 404,我们就不再读取数据。以下是一个处理连接中 404 错误的样例程序:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class ReadFromURL {

    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.example.com");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
                reader.close();
            } else {
                System.out.println("Error: " + responseCode);
            }
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

在这个样例程序中,我们使用了 Java 的 HttpURLConnection 类来处理连接中的 404 错误。getResponseCode 方法用于获取连接的响应码。

结论

使用 Java 的 URL 类和 HttpURLConnection 类,我们可以从连接中读取数据,即使连接中出现 404 错误。我们需要使用类似 getResponseCode 方法来检查连接中的响应码,并根据响应码来处理连接中的错误。