在 Retrofit 接口中定义一个 "base Url"

Define a "base Url" in a Retrofit Interface

我使用 Retrofit (https://square.github.io/retrofit/) 为 REST 服务创建了一个 Java 库。

我有一个如下所示的界面:

public interface OrganizationUnitsApi {

    @GET("organizationUnits")
    Call<List<OrganizationUnit>> getOrganizationUnits();

    @GET("organizationUnits/{organizationUnitId}")
    Call<OrganizationUnit> getOrganizationUnit(@Path("organizationUnitId") String organizationUnitId);
}

如您所见,我两次都解析到端点“organizationUnits”,所以我的请求最终将发送到“https://myservice.com/organizationUnits...”

是否有可能在 Retrofit 中为这个接口“注释”一个基础 Url? 也许是这样的?

@Path("organizationUnits")
public interface OrganizationUnitsApi {

    @GET("/")
    Call<List<OrganizationUnit>> getOrganizationUnits();

    @GET("{organizationUnitId}")
    Call<OrganizationUnit> getOrganizationUnit(@Path("organizationUnitId") String organizationUnitId);
}

目前没有这样的 API 在改造中类似于您正在尝试做的事情。但是,如果你必须这样做,你可以在构建 retorfit 对象时将 organizationUnits 作为 baseUrl 的一部分传递。

所以现在你正在做这样的事情

Retrofit.Builder().baseUrl(someUrl)

您可以改为执行以下操作

Retrofit.Builder().baseUrl(someUrl/organizationUnitId)

但在那种情况下,如果您对多个 API 接口使用相同的基础 url,您将不得不做额外的麻烦来单独配置它们。