我有一些具有相同 baseUrl 的服务 URL。对于一些 url 会有一些常用的参数,例如 apiVersion
或 locale
。但它们不必在每个 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/