WebsiteStatusChecker.java
· 1.2 KiB · Java
原始文件
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
public class WebsiteStatusChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the website URL to check: ");
String urlToCheck = scanner.nextLine();
try {
int statusCode = checkWebsiteStatus(urlToCheck);
if (statusCode >= 200 && statusCode < 400) {
System.out.println("Website is alive (HTTP Status Code: " + statusCode + ")");
} else {
System.out.println("Website is down (HTTP Status Code: " + statusCode + ")");
}
} catch (IOException e) {
System.err.println("Error checking website status: " + e.getMessage());
}
}
public static int checkWebsiteStatus(String url) throws IOException {
URL websiteURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) websiteURL.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int statusCode = connection.getResponseCode();
connection.disconnect();
return statusCode;
}
}
| 1 | import java.io.IOException; |
| 2 | import java.net.HttpURLConnection; |
| 3 | import java.net.URL; |
| 4 | import java.util.Scanner; |
| 5 | |
| 6 | public class WebsiteStatusChecker { |
| 7 | public static void main(String[] args) { |
| 8 | Scanner scanner = new Scanner(System.in); |
| 9 | System.out.print("Enter the website URL to check: "); |
| 10 | String urlToCheck = scanner.nextLine(); |
| 11 | |
| 12 | try { |
| 13 | int statusCode = checkWebsiteStatus(urlToCheck); |
| 14 | |
| 15 | if (statusCode >= 200 && statusCode < 400) { |
| 16 | System.out.println("Website is alive (HTTP Status Code: " + statusCode + ")"); |
| 17 | } else { |
| 18 | System.out.println("Website is down (HTTP Status Code: " + statusCode + ")"); |
| 19 | } |
| 20 | } catch (IOException e) { |
| 21 | System.err.println("Error checking website status: " + e.getMessage()); |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | public static int checkWebsiteStatus(String url) throws IOException { |
| 26 | URL websiteURL = new URL(url); |
| 27 | HttpURLConnection connection = (HttpURLConnection) websiteURL.openConnection(); |
| 28 | connection.setRequestMethod("GET"); |
| 29 | connection.connect(); |
| 30 | int statusCode = connection.getResponseCode(); |
| 31 | connection.disconnect(); |
| 32 | |
| 33 | return statusCode; |
| 34 | } |
| 35 | } |
| 36 |