17

我有一些具有相同 baseUrl 的服务 url。对于某些 url,会有一些常用的参数,例如 an apiVersionor locale。但它们不必在每个 url 中,所以我不能将它们添加到 baseUrl。

.../api/{apiVersion}/{locale}/event/{eventId}
.../api/{apiVersion}/{locale}/venues
.../api/{apiVersion}/configuration

我不想在改造界面中添加这些参数。在改造 1 中,我做了一个拦截器,用于RequestFacade.addPathParam(..., ...)为每个 url 填充这些公共路径参数。

对于改造 2,我似乎找不到使用 okhttp 执行此操作的正确方法。我现在看到这可能的唯一方法是HttpUrlChain.request().httpUrl();okhttp 中获取Interceptor并自己操作那个,但我不知道这是否是最好的方法。

有没有人遇到过更好的方法来替换 okhttp 中的路径参数Interceptor

在撰写本文时,我使用的是 retrofit:2.0.0-beta2 和 okhttp:2.7.2。

4

2 回答 2

8

对于改造 2,我似乎找不到使用 okhttp 执行此操作的正确方法。我现在看到这可能的唯一方法是从 Chain.request().httpUrl(); 获取 HttpUrl;在 okhttp 拦截器中并自己操作那个拦截器,但我不知道这是否是最好的方法。

我使用 okhttp:3.2 的实现

    class PathParamInterceptor implements Interceptor {
        private final String mKey;
        private final String mValue;

        private PathParamInterceptor(String key, String value) {
            mKey = String.format("{%s}", key);
            mValue = value;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();

            HttpUrl.Builder urlBuilder = originalRequest.url().newBuilder();
            List<String> segments = originalRequest.url().pathSegments();

            for (int i = 0; i < segments.size(); i++) {
                if (mKey.equalsIgnoreCase(segments.get(i))) {
                    urlBuilder.setPathSegment(i, mValue);
                }
            }

            Request request = originalRequest.newBuilder()
                    .url(urlBuilder.build())
                    .build();
            return chain.proceed(request);
        }
    }
于 2016-04-29T10:59:46.530 回答
-1

您好,您可以这样使用:

@GET("/api/{apiVersion}/{locale}/venues")
Call<FilterResponse> getLocaleVenues
          @Path("apiVersion") int apiVersion,
          @Path("locale") String locale
);

希望能帮助到你。

于 2019-11-29T06:47:17.530 回答