Give the following:
HttpURLConnection yc = (HttpURLConnection) dest.openConnection(); yc.setInstanceFollowRedirects( true );
In the context of your code above:
`String url = "http://java.sun.com"; String inputLine; StringBuilder srcCode=new StringBuilder(); URL dest = new URL(url); HttpURLConnection yc = (HttpURLConnection) dest.openConnection(); yc.setInstanceFollowRedirects( true ); yc.setUseCaches(false); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); while ((inputLine = in.readLine()) != null) { srcCode = srcCode.append (inputLine); } in.close();`
Modified further to help you determine what is happening. This code disables automatic redirection, and then manually prints out the location headers when it goes.
@Test public void f() throws IOException { String url = "http://java.sun.com"; fetchURL(url); } private HttpURLConnection fetchURL( String url ) throws IOException { URL dest = new URL(url); HttpURLConnection yc = (HttpURLConnection) dest.openConnection(); yc.setInstanceFollowRedirects( false ); yc.setUseCaches(false); System.out.println( "url = " + url ); int responseCode = yc.getResponseCode(); if ( responseCode >= 300 && responseCode < 400 ) {
source share