java urlconnection get the final redirected URL

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

    public static String getFinalRedirectedUrl(String url) {
    
        HttpURLConnection connection;
        String finalUrl = url;
        try {
            do {
                connection = (HttpURLConnection) new URL(finalUrl)
                        .openConnection();
                connection.setInstanceFollowRedirects(false);
                connection.setUseCaches(false);
                connection.setRequestMethod("GET");
                connection.connect();
                int responseCode = connection.getResponseCode();
                if (responseCode >= 300 && responseCode < 400) {
                    String redirectedUrl = connection.getHeaderField("Location");
                    if (null == redirectedUrl)
                        break;
                    finalUrl = redirectedUrl;
                    System.out.println("redirected url: " + finalUrl);
                } else
                    break;
            } while (connection.getResponseCode() != HttpURLConnection.HTTP_OK);
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return finalUrl;
    }
    

提交回复
热议问题