Java获取网页错误信息
时间: 2024-09-18 13:00:39 浏览: 53
在Java中,获取网页错误信息通常涉及到网络请求库,比如Apache HttpClient、OkHttp或者更现代的Java HttpURLConnection。当你尝试从互联网上获取数据时,可能会遇到各种HTTP状态码,这些状态码表示了请求的结果。例如:
1. **404 Not Found** - 页面未找到,意味着服务器找不到请求的资源。
2. **500 Internal Server Error** - 服务器内部错误,可能是服务端的问题。
获取这些错误信息的基本步骤如下:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
public class WebRequestExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com"; // 替换为你需要访问的网址
try (HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection()) {
int responseCode = connection.getResponseCode();
if (responseCode >= 400) { // 大多数错误代码范围在此
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
String errorLine;
System.out.println("Error code: " + responseCode);
while ((errorLine = reader.readLine()) != null) {
System.out.println("Error message: " + errorLine);
}
reader.close();
} else {
System.out.println("Success! Status code: " + responseCode);
}
}
}
}
```
在这个例子中,如果响应码不是200(成功),程序会读取并打印错误消息流。记得处理异常,因为网络连接可能会失败。
阅读全文
相关推荐


















