改造 - 使用带前缀的查询参数

Retrofit - use query parameter with prefix

我有一个小问题想解决。我需要为以下请求创建改造服务

https://www.googleapis.com/books/v1/volumes?q=isbn:9788087270431

我的 API 目前看起来像:

public interface GoogleBooksApi {

    @GET("/books/v1/volumes")
    Call<BookResponse> getBooksByIsbn(@Query("q") String isbn);

}

但我每次都必须使用前缀"isbn:"。有人可以告诉我如何正确执行此操作吗?

这里的问题似乎是您误解了调用 getBooks 所期望的实际参数。

@GET("/books/v1/volumes")
Call<BookResponse> getBooksByIsbn(@Query("q") String isbn);

实际上应该是

@GET("/books/v1/volumes")
Call<BookResponse> getBooks(@Query("q") String query);

然后您可以将对 API 的调用包装在如下调用中:

public void findByIsbn(String isbn) {
    GoogleBooksApi api = restAdapter.create(GoogleBooksApi.class);
    String query = buildIsbnQuery(isbn);
    api.getBooks(query);
}

public String buildIsbnQuery(String isbn) {
    return String.format("isbn:%s");
}

这样,如果要求不再是 ISBN 的要求,您不必更改 api 代码的实际功能,您只需要添加一个额外的查询构建器方法,这使得它尊重open-closed principal.

不建议更改改造代码,也完全没有必要。