android - 将retrofit 2中的公共(public)路径参数替换为okhttp

标签 android okhttp retrofit2

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

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

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

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

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

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

最佳答案

For retrofit 2, I can't seem to find a proper way to do this with okhttp. The only way I see this being possible right now is to get the HttpUrl from Chain.request().httpUrl(); in an okhttp Interceptor and manipulate that one myself, but I don't know if this is the best way to go.

我使用 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);
        }
    }

关于android - 将retrofit 2中的公共(public)路径参数替换为okhttp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34724222/

相关文章:

java - 执行查询时出现 SQLiteException

android - okHttp3 response.code() 不会返回 304

android - 应为 BEGIN_OBJECT 但在第 1 行第 2 列路径处为 BEGIN_ARRAY

android - 在 Jetpack Compose 中的 API 响应后更新 LazyColumn

android - 为什么异步方法在 Retrofit 2 中调用得更快?

java - Logback - 使用多个实例

android - 将两个 TextView 放在包含 Google map 的 fragment 上方

android - Android 中的 Intent 附加功能

android - 如何使用 OkHttp 3.2.0 在 Picasso 2.5.2 中添加基本身份验证

android - 现在 SSLSocketFactory 在 Android 上已被弃用,处理客户端证书身份验证的最佳方法是什么?