1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Java】リダイレクトされた最終URLを取得する方法

Posted at

概要

あるURLをリクエストするとリダイレクトされる場合があります。リダイレクトされた最終のURLを取得する方法のメモです。

コード

ライブラリにはokhttp3をつかう

リダイレクトされた最終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();
    }
}

実行する側のクラス

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);
    }
}

依存関係(maven)

以下をpom.xmlに追加する

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.13.1</version>
</dependency>

実行結果

Example.javaを実行すると、リダイレクトされた最終のURLが取得できた。

original url=https://qiita.com/settings/account
final url=https://qiita.com/login?redirect_to=https%3A%2F%2Fqiita.com%2Fsettings%2Faccount
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?