我正在使用Retrofit2连接到基于REST的API。问题是它需要lat / lng位置,但仅适用于大约50%的端点。我想知道如何根据一些布尔值动态地将查询参数添加到OkHttpClient中。我现在的代码:
public static APIEndpointInterface getHttpClient(Boolean addLatLng){
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
LatLng location = App.getLocationRepository().getCurrentLocation();
String lat = String.valueOf(location.latitude);
String lng = String.valueOf(location.longitude);
Request request = chain.request();
HttpUrl url = request.url().newBuilder()
.addQueryParameter("version", API_VERSION)
.addQueryParameter("app_version_code", String.valueOf(BuildConfig.VERSION_CODE))
//ADD ONLY IF BOOLEAN PASSED TO METHOD IS TRUE
.addQueryParameter("lat", lat)
.addQueryParameter("lng", lng)
.port(PORT_HTTPS)
.build();
......
除了为每个第二个接口方法添加lat / lng还有其他选择吗?
答案 0 :(得分:0)
我自己刚刚找到了解决方案。如果它可以帮助任何人:
Request request = chain.request();
HttpUrl.Builder builder = request.url().newBuilder();
builder.addQueryParameter("version", API_VERSION);
builder.addQueryParameter("app_version_code",String.valueOf(BuildConfig.VERSION_CODE));
if (location) {
builder.addQueryParameter("lat", lat);
builder.addQueryParameter("lng", lng);
}
HttpUrl url = builder.build();
request = request.newBuilder()
.addHeader("Accept", "application/json")
.url(url)
.build();