-1

I'm trying to get a redirected URL from newURLConnection, but when I print out, it still outputs what the URL is before it is redirected. I'm certain that the original newURLConnection is a legitimate URL because when I enter it into a web browser it redirects automatically. I've tried it with conn.setInstanceFollowRedirects set to both false and true, and neither works...for some reason it's just impossible for me to get the redirected URL. Help would definitely be appreciated.

//open a connection
                URLConnection newURLConnection = params[0].openConnection();
                HttpURLConnection conn =  (HttpURLConnection) newURLConnection;
                //following code sourced from mkyong.com
                conn.setInstanceFollowRedirects(true);
                //HttpURLConnection.setFollowRedirects(true);
                conn.connect();
                //get the redirected URL
                InputStream newURLConnectedStream = conn.getInputStream();
                System.out.println("" + conn.getURL());
2____
  • 167
  • 2
  • 14
  • Possible duplicate of [java, android, resolve an url, get redirected uri](http://stackoverflow.com/questions/5204599/java-android-resolve-an-url-get-redirected-uri) – Gemtastic May 03 '17 at 05:31

1 Answers1

3

Try the following code to get it,

URL url = new URL(url);
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
URLConnection conn = secondURL.openConnection();

Copied from java, android, resolve an url, get redirected uri

Community
  • 1
  • 1
sadat
  • 4,004
  • 2
  • 29
  • 49