java - Java URL 检查 404 HTTP 响应代码
问题描述
我从URL
Java 中的一个类型中读取并逐行获取输出。但是如果页面不存在,它会抛出一个404
错误代码。
如何添加检查响应代码是否为200
(而不是404
),获取该行?如果是404
,打印一些东西。
url = new URL("http://my.address.com/getfile/12345.txt");
Scanner s = new Scanner(url.openStream());
while (s.hasNextLine()) {
s.nextLine();
break;
}
解决方案
try {
URL url = new URL("https://www.google.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {// status 200
Scanner s = new Scanner(url.openStream());
while (s.hasNextLine()) {
s.nextLine();
break;
}
}else if(code == HttpURLConnection.HTTP_NOT_FOUND){//status 404
// TODO: url not found
}else{
// TODO: other reponse status
}
}
catch (IOException ex) {
Logger.getLogger(Week8.class.getName()).log(Level.SEVERE, null, ex);
}
这是您的方案的示例代码。我使用谷歌网站作为 URL。
推荐阅读
- r - 如何在 mutate 调用中访问函数中的列名?
- django - 如何根据 http 方法将请求发送到某个视图?
- objectgears - 在 ObjectGears 中设置值的多个规则
- firebase - 使用 Firebase Cloud Functions 实施 Cloud Run
- bash - 在适用于 Linux 的 Windows 子系统 (WSL) 中查找活动的串行端口
- api - 从 angular8 到达端点返回 404
- java - Android:保护资源
- vba - for循环中的错误1004如何转到下一个函数
- python - 是否可以对使用子进程的代码运行单元测试?
- python - 带有网格搜索的 AdaBoost 不能使用 permutation_test_score