import java.net.HttpURLConnection; import java.net.URL; public class URLUtils { /** * Prints the redirect URL for the provided input URL (if it applies). * @param url */ public static void printRedirect(String url) { try { URL urlToPing = new URL(url); HttpURLConnection urlConn = (HttpURLConnection) urlToPing.openConnection(); // Needed to check if it is a redirect. urlConn.setInstanceFollowRedirects(false); // It's any of these response codes: 301/302/303 if (urlConn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || urlConn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP || urlConn.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) { System.out.println("URL <" + url + "> redirects to: <" + urlConn.getHeaderField("Location") + ">, Response Code: " + +urlConn.getResponseCode()); } else { System.out.println("URL <" + url + "> has no redirect, Response Code: " + urlConn.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { URLUtils.printRedirect("http://www.google.com"); URLUtils.printRedirect("http://www.crjug.org"); } }
Result:
URL <http://www.google.com> redirects to: <http://www.google.co.cr/>, Response Code: 302 URL <http://www.crjug.org> has no redirect, Response Code: 200
No comments:
Post a Comment