I’m sure while working on Java Web Project, you must have faced these kind of questions:
- How to get HTTP response code for a URL in Java?
- How to check if a URL exists or returns 404 with Java?
- How can I read the status code of a HTTP request?
- How to get HTTP code from org.apache.http.HttpResponse?
- How to check if my Tomcat is up and running?
Well, below simple Java Program will answer all your mentioned questions. Do let me know if you see any problem.
package crunchify.com.tutorials; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; /** * @author Crunchify.com * */ public class CrunchifyGetPingStatus { public static void main(String args[]) throws Exception { String[] hostList = { "https://crunchify.com", "https://yahoo.com", "https://www.ebay.com", "https://google.com", "https://www.example.co", "https://paypal.com", "https://bing.com/", "https://techcrunch.com/", "https://mashable.com/", "https://thenextweb.com/", "https://wordpress.com/", "https://wordpress.org/", "https://example.com/", "https://sjsu.edu/", "https://ebay.co.uk/", "https://google.co.uk/", "https://wikipedia.org/" }; for (int i = 0; i < hostList.length; i++) { String url = hostList[i]; getStatus(url); } System.out.println("Task completed..."); } public static String getStatus(String url) throws IOException { String result = ""; int code = 200; try { URL siteURL = new URL(url); HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(3000); connection.connect(); code = connection.getResponseCode(); if (code == 200) { result = "-> Green <-\t" + "Code: " + code; ; } else { result = "-> Yellow <-\t" + "Code: " + code; } } catch (Exception e) { result = "-> Red <-\t" + "Wrong domain - Exception: " + e.getMessage(); } System.out.println(url + "\t\tStatus:" + result); return result; } }
Output:
https://crunchify.com Status:-> Yellow <- Code: 301 https://yahoo.com Status:-> Yellow <- Code: 301 https://www.ebay.com Status:-> Yellow <- Code: 301 https://google.com Status:-> Green <- Code: 200 https://www.example.co Status:-> Red <- Wrong domain - Exception: www.example.co https://paypal.com Status:-> Green <- Code: 200 https://bing.com/ Status:-> Green <- Code: 200 https://techcrunch.com/ Status:-> Yellow <- Code: 301 https://mashable.com/ Status:-> Yellow <- Code: 301 https://thenextweb.com/ Status:-> Green <- Code: 200 https://wordpress.com/ Status:-> Yellow <- Code: 301 https://wordpress.org/ Status:-> Yellow <- Code: 301 https://example.com/ Status:-> Green <- Code: 200 https://sjsu.edu/ Status:-> Red <- Wrong domain - Exception: connect timed out https://ebay.co.uk/ Status:-> Yellow <- Code: 301 https://google.co.uk/ Status:-> Green <- Code: 200 https://wikipedia.org/ Status:-> Yellow <- Code: 301 Task completed...
If you are interested on more than 10 java tutorials then check this out.