--Get the URL of the HTTP redirect destination in Java
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
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
Recommended Posts