URLAccessibleChecker.java 999 B

1234567891011121314151617181920212223242526272829
  1. import java.io.IOException;
  2. import java.net.HttpURLConnection;
  3. import java.net.URL;
  4. public class URLAccessibleChecker {
  5. public static boolean isURLAccessible(String url) {
  6. try {
  7. URL u = new URL(url);
  8. HttpURLConnection huc = (HttpURLConnection) u.openConnection();
  9. huc.setRequestMethod("GET");
  10. huc.setRequestProperty("User-Agent", "Mozilla/5.0");
  11. huc.setRequestProperty("Accept", "*/*");
  12. huc.setConnectTimeout(5000); // 5 seconds timeout
  13. huc.connect();
  14. int responseCode = huc.getResponseCode();
  15. // HTTP OK status returned.
  16. return (200 <= responseCode && responseCode <= 399);
  17. } catch (IOException e) {
  18. e.printStackTrace();
  19. return false;
  20. }
  21. }
  22. public static void main(String[] args) {
  23. String testUrl = "http://肥猫.com";
  24. System.out.println("Is URL accessible? " + isURLAccessible(testUrl));
  25. }
  26. }