You may be redirected when you request a URL. A note on how to get the final redirected URL.
Use okhttp3 for the library
Class to get the final redirected URL
RedirectFinalUrlResolver.java
package example;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class FinalUrlResolver {
private OkHttpClient mClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
return chain.proceed(chain.request());
}
})
.build();
public String get(String url) throws IOException {
final Response r = mClient.newCall(new Request.Builder().url(url).build()).execute();
return r.request().url().toString();
}
}
** Executing class **
Example.java
package example;
import java.io.IOException;
public class Example {
public static void main(String[] args) throws IOException {
FinalUrlResolver o=new FinalUrlResolver();
String url="https://qiita.com/settings/account";
String finalUrl=o.get(url);
System.out.println("original url="+url);
System.out.println("final url="+finalUrl);
}
}
Add the following to pom.xml
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.13.1</version>
</dependency>
When I ran ** Example.java **, I got the final redirected URL.
original url=https://qiita.com/settings/account
final url=https://qiita.com/login?redirect_to=https%3A%2F%2Fqiita.com%2Fsettings%2Faccount
Recommended Posts