Method 1
UseJava.netThe URL class below implements that the URL is a reference to a uniform resource identifier, a URL instance represents a reference to a url, and then the openStream() method in the URL is used.
java code:
[java] view plain copy
import java.io.InputStream; import java.net.URL; public class URLTest { public static void testUrl(String webUrl) { URL url; try { url = new URL(webUrl); InputStream inputStream = url.openStream(); System.out.println("Connection available!"); } catch (Exception e) { e.printStackTrace(); System.out.println("Connection not available!"); url = null; } } public static void main(String[] args) { URLTest.testUrl("https://www.baidu.com"); } }
Method 2
UseJava.netThe URL and HttpURLConnection classes below are implemented.It uses the getResponseCode() method in the HttpURLConnection, usually an instance of the HttpURLConnection can generate a request, and it has a method getResponseCode() to get the response status of the request, which returns an int of 200 and 404, respectively, and -1 if no code can be identified from the response.
Java code:
[java] view plain copy
import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class URLTest { public static boolean testUrl(String webUrl) { try { // Sets whether this class should automatically perform HTTP redirection (response code is 3xx for requests). HttpURLConnection.setFollowRedirects(false); // Connection to remote object referenced by URL HttpURLConnection conn = (HttpURLConnection) new URL(webUrl).openConnection(); // Set the method of URL request, GET POST HEAD OPTIONS PUT DELETE TRACE // One of the above methods is legal, depending on the limitations of the agreement. conn.setRequestMethod("HEAD"); // Get status code from HTTP response message return (conn.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { e.printStackTrace(); return false; } } public static void main(String[] args) { URLTest.testUrl("https://www.baidu.com"); } }