我们从服务器获取URL路径,但还必须在此之上添加查询参数。在翻新中,这会导致->
/some/path/%3Fquery1=1?query2=1&query3=1
我有一个自定义的拦截器(请参阅文章的底部)来处理此问题,但我觉得这是一种糟糕的方法。有什么更好的方法可以做到这一点,以便正确格式化吗?
其他信息:
这是我们从服务器获取的路径(在调用之前添加了基本URL)->
/apps/my-app/category/modules/?value=1min
这是我的自定义拦截器->
package com.my.package.api;
import android.support.annotation.NonNull;
import java.io.IOException;
import java.util.List;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class MyApiInterceptor implements Interceptor {
// Query Params
private static final String OS = "os";
private static final String API_VERSION = "apiVersion";
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request.Builder requestBuilder = chain.request().newBuilder();
HttpUrl.Builder httpUrlBuilder = chain.request().url().newBuilder(); //"/apps/my-app/category/modules/?value=1min"
List<String> segments = chain.request().url().pathSegments();
for (int i = 0; i < segments.size(); i++) {
if (segments.get(i).contains("?value")) {
String[] parts = segments.get(i).split("\\?");
if (parts.length == 2) {
httpUrlBuilder.removePathSegment(i);
httpUrlBuilder.addEncodedPathSegments(parts[0]);
String[] keyValue = parts[1].split("=");
httpUrlBuilder.addQueryParameter(keyValue[0], keyValue[1]);
}
break;
}
}
httpUrlBuilder.addQueryParameter(OS, "android");
httpUrlBuilder.addQueryParameter(API_VERSION, "12");
requestBuilder.url(httpUrlBuilder.build());
return chain.proceed(requestBuilder.build());
}
}