Sie*_*ebe 13 android okhttp retrofit2
我有一些具有相同baseUrl的服务URL.对于某些网址,会有一些常用的参数,例如apiVersion或locale.但它们不必存在于每个URL中,因此我无法将它们添加到baseUrl中.
.../api/{apiVersion}/{locale}/event/{eventId}
.../api/{apiVersion}/{locale}/venues
.../api/{apiVersion}/configuration
Run Code Online (Sandbox Code Playgroud)
我不想在改装界面中添加这些参数.在改造1中,我制作了一个拦截器并用于RequestFacade.addPathParam(..., ...)填充每个URL的这些常用路径参数.
对于改造2,我似乎找不到用okhttp做这个的正确方法.我现在看到这种可能性的唯一方法是HttpUrl从Chain.request().httpUrl();一个okhttp中获取Interceptor并自己操纵那个,但我不知道这是否是最好的方法.
有没有人遇到过更好的方法来替换okhttp中的路径参数Interceptor?
在撰写本文时,我正在使用改进:2.0.0-beta2和okhttp:2.7.2.
小智 6
对于改造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);
}
}
Run Code Online (Sandbox Code Playgroud)