Retrofit2如何获取重定向网址@HEAD(“/”)

时间:2016-05-31 14:17:00

标签: java android retrofit retrofit2

我有一个缩小的网址,我想拥有最终的网址

使用Retrofit 1.9我曾经这样做过:

@HEAD("/XXXXXXXXX")
void fetchFinalUrl(Callback<String> cb);


public void getUrl() {
   mMinifyService.fetchFinalUrl(new Callback<String>() {
                @Override
                public void success(String s, Response response) {
                    response.getUrl();
                }
                [...]
}

但现在有了Retrofit 2 .getUrl()不存在任何想法怎么做?

提前致谢。

修改

终于搞定了!

public class ApiProvider<T> {

    private Retrofit retrofit;
    private static final String END_POINT_MINIFY = "XXXXXXX";

    public ApiProvider() {
        initAdapter();
    }

    public T getService(Class<T> service) {
        return retrofit.create(service);
    }

    private void initAdapter() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .followRedirects(false)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl(END_POINT_MINIFY)
                .addConverterFactory(new ToStringConverterFactory())
                .client(client)
                .build();
    }

}

public interface IMinifyService {
    @HEAD("/XXXXXXXXX")
    Call<Void> fetchFinalUrl(Callback<String> cb);
}


public class MinifyServiceImpl {

    private ApiProvider<IMinifyService> mApiProvider = new ApiProvider<>();
    private IMinifyService mMinifyService = mApiProvider.getService(IMinifyService.class);

    public Promiser<String, Integer> fetchMinifyUrl() {
        return new Promiser<>((resolve, reject) -> mMinifyService.fetchMinifyUrl().enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.code() >= 300 && response.code() < 400){
                    resole.run(response.headers().get("Location"));
                } else {
                    reject.run(response.code());
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                reject.run(t.hashCode());
            }
        }));
    }

}

如果你想使用Promizer - &gt; Click here

1 个答案:

答案 0 :(得分:1)

response.raw().request().url()