Retrofit 2 – Dynamic URL – 改造2 – 动态URL

最后修改: 2020年 10月 28日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this short tutorial, we’ll learn how to create a dynamic URL in Retrofit2.

在这个简短的教程中,我们将学习如何Retrofit2中创建一个动态URL

2. @Url Annotation

2.@Url注释

There are cases when we need to use a dynamic URL in our application during runtime. Version 2 of the Retrofit library introduced the @Url annotation that allows us to pass a complete URL for an endpoint:

有些情况下,我们需要在运行期间在我们的应用程序中使用一个动态的URL。Retrofit 库的第2版引入了@Url注解,允许我们为一个端点传递一个完整的URL

@GET
Call<ResponseBody> reposList(@Url String url);

This annotation is based on the HttpUrl class from OkHttp’s library, and the URL address is solved like a link on a page using <a href=“”>. When using the @Url parameter, we don’t need to specify the address in the @GET annotation.

这个注解是基于OkHttpUrl库中的OkHttp的类,URL地址像页面上的链接一样使用<a href=“”>解决。当使用@Url参数时,我们不需要在@GET注释中指定地址。

The @Url parameter replaces our baseUrl from the service implementation:

@Url参数取代了我们来自服务实现的baseUrl

Retrofit retrofit = new Retrofit.Builder()
  .baseUrl("https://api.github.com/")
  .addConverterFactory(GsonConverterFactory.create()).build();

What is important is that if we want to use the @Url annotation, it must be set as the first parameter in the service method.

重要的是,如果我们想使用@Url注解,它必须被设置为服务方法的第一个参数。

3. Path Param

3.路径参数

If we know that some part of our base URL will be constant, but we don’t know the extension of it or the number of parameters that will be used, we can use the @Path annotation and the encoded flag:

如果我们知道我们的基本URL的某些部分将是恒定的,但我们不知道它的扩展名或将使用的参数数量,我们可以使用@Path注释和encoded标志。

@GET("{fullUrl}")
Call<List<Contributor>> contributorsList(@Path(value = "fullUrl", encoded = true) String fullUrl);

This way, all “/” won’t be replaced by %2F, as if we had not used the encoded parameter. However, all characters “?” in the passed address still will be replaced by %3F.

这样,所有的”/”就不会被替换成%2F,就像我们没有使用编码的参数一样。然而,传递的地址中的所有字符”?”仍然会被%3F.所取代。

4. Summary

4.摘要

The Retrofit library allows us to easily provide a dynamic URL during application runtime by using only the @Url annotation.

Retrofit库允许我们仅通过使用@Url注解,在应用程序运行期间轻松提供一个动态URL。

As usual, all code examples can be found over on GitHub.

像往常一样,所有的代码例子都可以在GitHub上找到