Get the URL of the HTTP redirect destination in Java

Overview

--Get the URL of the HTTP redirect destination in Java

Java 11 version

Save the following contents with the file name GetRedirect.java.

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Optional;

public class GetRedirect {

  public static void main(String[] args) throws Exception {

    //Get command line arguments
    String srcUrl = args[0];

    //Get the redirect URL
    Optional<String> redirectUrl = getRedirectUrl(srcUrl);

    //Output redirect URL
    redirectUrl.ifPresent(url -> System.out.println(url));
  }

  //Get the redirect URL
  public static Optional<String> getRedirectUrl(String srcUrl) throws URISyntaxException, IOException, InterruptedException {

    //Build HTTP request information
    HttpRequest req = HttpRequest.newBuilder(new URI(srcUrl)).GET().build();

    //HTTP request
    //Note that HttpClient does not raise an exception even with 4xx or 5xx
    HttpClient client = HttpClient.newBuilder()
      .version(HttpClient.Version.HTTP_1_1)
      .followRedirects(HttpClient.Redirect.NEVER) //Setting not to redirect automatically
      .build();
    HttpResponse<String> res = client.send(req, HttpResponse.BodyHandlers.ofString());

    //Get Location header from HTTP response
    return res.headers().firstValue("location");
  }
}

Execution example by Java 11 (AdoprOpenJDK 11.0.8) + macOS Catalina.

$ java GetRedirect.java https://bit.ly/3kmTOkc
https://t.co/yITSBp4ino
$ java GetRedirect.java https://t.co/yITSBp4ino
https://qiita.com/niwasawa
$ java GetRedirect.java https://qiita.com/niwasawa

Java 8 version

Save the following contents with the file name GetRedirect.java.

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetRedirect {

  public static void main(String[] args) throws IOException {

    //Get command line arguments
    String srcUrl = args[0];

    //Get the redirect URL
    String redirectUrl = getRedirectUrl(srcUrl);

    //Output redirect URL
    if (redirectUrl != null) {
      System.out.println(redirectUrl);
    }
  }

  //Get the redirect URL
  public static String getRedirectUrl(String srcUrl) throws IOException {
    //Note that 4xx and 5xx do not raise an exception
    HttpURLConnection con = (HttpURLConnection) new URL(srcUrl).openConnection();
    con.setRequestMethod("GET");
    con.setInstanceFollowRedirects(false); //Setting not to redirect automatically
    con.connect();
    //Get Location header from HTTP response
    String location = con.getHeaderField("location");
    con.disconnect();
    return location;
  }
}

Execution example by Java 8 (AdoprOpenJDK 1.8.0_265) + macOS Catalina.

compile.

$ javac GetRedirect.java

Run.

$ java GetRedirect https://bit.ly/3kmTOkc
https://t.co/yITSBp4ino
$ java GetRedirect https://t.co/yITSBp4ino
https://qiita.com/niwasawa
$ java GetRedirect https://qiita.com/niwasawa

Reference material

Recommended Posts

Get the URL of the HTTP redirect destination in Java
Get the URL of the HTTP redirect destination in Ruby
Source used to get the redirect source URL in Java
Get the result of POST in Java
Get the public URL of a private Flickr file in Java
[Java] How to get the URL of the transition source
[Java] Get the file in the jar regardless of the environment
[Rails] How to get the URL of the transition source and redirect
[Java] Get the dates of the past Monday and Sunday in order
[Java] Get the day of the specific day of the week
How to get the date in java
The story of writing Java in Emacs
How to get the length of an audio file in java
How to get the absolute path of a directory running in Java
The story of low-level string comparison in Java
[Java] Handling of JavaBeans in the method chain
The story of making ordinary Othello in Java
About the idea of anonymous classes in Java
[Java] Access the signed URL of s3 (signed version 2)
The story of learning Java in the first programming
Measure the size of a folder in Java
[Java] Get the length of the surrogate pair string
Feel the passage of time even in Java
[Java] How to get the redirected final URL
[Java] How to get the authority of the folder
Import files of the same hierarchy in Java
[Rails] Get the path name of the URL before the transition and change the link destination
Login fails because the redirect URL of the self-login screen is incorrect in spring-security
Sample code to get the values of major SQL types in Java + MySQL 8.0
Get the name of the test case in the JUnit test class
[Java] How to get the maximum value of HashMap
[Java] Get the file path in the folder with List
Change the storage quality of JPEG images in Java
Summarize the additional elements of the Optional class in Java 9
Replace only part of the URL host with java
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
Get EXIF information in Java
[Java] Get KClass in Java [Kotlin]
Implementation of gzip in java
Implementation of tri-tree in Java
How to get the class name / method name running in Java
Was done in the base year of the Java calendar week
A quick explanation of the five types of static in Java
Get the next business day after the specified date in JAVA
Get to the abbreviations from 5 examples of iterating Java lists
Count the number of digits after the decimal point in Java
Correct the character code in Java and read from the URL
How to derive the last day of the month in Java
[Ruby on Rails] I want to get the URL of the image saved in Active Storage
Sample code to get the values of major SQL types in Java + Oracle Database 12c
Access the network interface in Java
[Java] Delete the elements of List
[Java] Get date information 10 days later using milliseconds in the Date class
Guess the character code in Java
Examine the system information of AWS Lambda operating environment in Java
[Java1.8 +] Get the date of the next x day of the week with LocalDate
[Java version] The story of serialization
Get a proxy instance of the component itself in Spring Boot
Specify the java location in eclipse.ini
Output the difference between each field of two objects in Java
Find out the list of fonts available in AWS Lambda + Java