1234567891011121314151617181920212223242526272829 |
- import java.io.IOException;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class URLAccessibleChecker {
- public static boolean isURLAccessible(String url) {
- try {
- URL u = new URL(url);
- HttpURLConnection huc = (HttpURLConnection) u.openConnection();
- huc.setRequestMethod("GET");
- huc.setRequestProperty("User-Agent", "Mozilla/5.0");
- huc.setRequestProperty("Accept", "*/*");
- huc.setConnectTimeout(5000); // 5 seconds timeout
- huc.connect();
- int responseCode = huc.getResponseCode();
- // HTTP OK status returned.
- return (200 <= responseCode && responseCode <= 399);
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
- }
- public static void main(String[] args) {
- String testUrl = "http://肥猫.com";
- System.out.println("Is URL accessible? " + isURLAccessible(testUrl));
- }
- }
|