java urlconnection get the final redirected URL

后端 未结 7 1827
死守一世寂寞
死守一世寂寞 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:23

    This one goes recursively in case there are multiple redirects:

    protected String getDirectUrl(String link) {
        String resultUrl = link;
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) new URL(link).openConnection();
            connection.setInstanceFollowRedirects(false);
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                String locationUrl = connection.getHeaderField("Location");
    
                if (locationUrl != null && locationUrl.trim().length() > 0) {
                    IOUtils.close(connection);
                    resultUrl = getDirectUrl(locationUrl);
                }
            }
        } catch (Exception e) {
            log("error getDirectUrl", e);
        } finally {
            IOUtils.close(connection);
        }
        return resultUrl;
    }
    

提交回复
热议问题