Java HttpURLConnection get response code
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class Main { public static void main(String[] args) throws Exception { URL url = new URL("http://demo2s.com"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); System.out.println("Request URL ... " + url); int code = con.getResponseCode(); if ((code != HttpURLConnection.HTTP_OK) && // (code == HttpURLConnection.HTTP_MOVED_TEMP || // code == HttpURLConnection.HTTP_MOVED_PERM || // code == HttpURLConnection.HTTP_SEE_OTHER)) {// System.out.println("Response Code ... " + code); // get redirect url from "location" header field URL newUrl = new URL(con.getHeaderField("Location")); // open the connection again con = (HttpURLConnection) newUrl.openConnection(); System.out.println("Redirect to URL : " + newUrl); }// w ww . jav a2 s. c o m BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; StringBuffer htmlStr = new StringBuffer(); while ((line = in.readLine()) != null) htmlStr.append(line); in.close(); System.out.println("Content... \n" + htmlStr); } }