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 com.crunchify.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 = { "http://crunchify.com", "http://yahoo.com", "http://www.ebay.com", "http://google.com", "http://www.example.co", "https://paypal.com", "http://bing.com/", "http://techcrunch.com/", "http://mashable.com/", "http://thenextweb.com/", "http://wordpress.com/", "http://wordpress.org/", "http://example.com/", "http://sjsu.edu/", "http://ebay.co.uk/", "http://google.co.uk/", "http://www.wikipedia.org/", "http://en.wikipedia.org/wiki/Main_Page" }; for (int i = 0; i < hostList.length; i++) { String url = hostList[i]; String status = getStatus(url); System.out.println(url + "\t\tStatus:" + status); } } public static String getStatus(String url) throws IOException { String result = ""; try { URL siteURL = new URL(url); HttpURLConnection connection = (HttpURLConnection) siteURL .openConnection(); connection.setRequestMethod("GET"); connection.connect(); int code = connection.getResponseCode(); if (code == 200) { result = "Green"; } } catch (Exception e) { result = "->Red<-"; } return result; } }
Output:
http://crunchify.com Status:Green http://yahoo.com Status:Green http://www.ebay.com Status:Green http://google.com Status:Green http://www.example.co Status:->Red<- https://paypal.com Status:Green http://bing.com/ Status:Green http://techcrunch.com/ Status:Green http://mashable.com/ Status:Green http://thenextweb.com/ Status:Green http://wordpress.com/ Status:Green http://wordpress.org/ Status:Green http://example.com/ Status:Green http://sjsu.edu/ Status:Green http://ebay.co.uk/ Status:Green http://google.co.uk/ Status:Green http://www.wikipedia.org/ Status:Green http://en.wikipedia.org/wiki/Main_Page Status:Green
If you are interested on more than 10 java tutorials then check this out.
The post How to get Ping Status of any HTTP End Point in Java? appeared first on Crunchify.