java urlconnection get the final redirected URL

后端 未结 7 1828
死守一世寂寞
死守一世寂寞 2020-11-30 13:07

I have a url which redirects to another url.I want to be able to get the final redirected URL.My code:

    public class testURLConnection
    {
    public st         


        
7条回答
  •  甜味超标
    2020-11-30 13:21

    @JEETS Your fetchRedirectURL function may not work because there are a variety of HTTP codes for redirects. Change it to a range check and it will work.

    public static String fetchRedirectURL(String url) throws IOException
        {
    HttpURLConnection con =(HttpURLConnection) new URL( url ).openConnection();
    //System.out.println( "orignal url: " + con.getURL() );
    con.setInstanceFollowRedirects(false);
    con.connect();
    
    InputStream is = con.getInputStream();
    if(con.getResponseCode()>=300 && con.getResponseCode() <400)
        return con.getHeaderField("Location");
    else return null;
        }
    

提交回复
热议问题