Java:HTTPS URL不重定向

时间:2017-05-03 00:26:12

标签: java android http url redirect

我试图从newURLConnection获取重定向的网址,但是当我打印出来时,它仍会在重定向之前输出网址。我确定原始的newURLConnection是合法的URL,因为当我将其输入Web浏览器时,它会自动重定向。我已经尝试将conn.setInstanceFollowRedirects设置为false和true,并且都不起作用......由于某种原因,我无法获得重定向的URL。肯定会得到帮助。

//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());

1 个答案:

答案 0 :(得分:3)

尝试以下代码来获取它,

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

java, android, resolve an url, get redirected uri

复制