Avoid coding data when creating urls

I am trying to make a call as follows:

 @GET(AppConstants.BASE_URL + "{category_type}/")
    Call<JsonObject> callCustomFilterApI(@Path("category_type") String type,
                                         @QueryMap(encoded = true)  Map<String,String> fields ,
                                         @Query("page") String pageNo);

But it @QueryMapmay have "&" in the data, so modify it to% 26.

There is somehow "&" does not change to "% 26".

The solution I tried:

I pass the data to QueryMap as:

 private void callCustomFilterSearchPagesApi(String type,  ArrayList<FilterListWithHeaderTitle> customFiltersList, int pageNumber, final ApiInteractor listener) {
        Map<String, String> queryMap = new HashMap<>();

            for (FilterListWithHeaderTitle item: customFiltersList) {

                String pairValue;
                if (queryMap.containsKey(item.getHeaderTitle())){
                    // Add the duplicate key and new value onto the previous value
                    // so (key, value) will now look like (key, value&key=value2)
                    // which is a hack to work with Retrofit QueryMap

                    String oldValue=queryMap.get(item.getHeaderTitle());
                    String newValue="filters[" + item.getHeaderTitle() + "][]"
                            +oldValue+ "&"+"filters[" + item.getHeaderTitle() + "][]"+item.getFilterItem();
                    pairValue=newValue;
                }else {
                    // adding first time
                    pairValue= item.getFilterItem();
                }
                try {
                    //pairValue= URLEncoder.encode(pairValue, "utf-8");
                   // LoggerUtils.logE(TAG,pairValue);
                    //queryMap.put(item.getHeaderTitle(), Html.fromHtml(pairValue).toString());
                    queryMap.put(item.getHeaderTitle(), pairValue);

                }catch (Exception u){
                    LoggerUtils.crashlyticsLog(TAG,u.getMessage());
                }

            }
            Call<JsonObject> call = TagTasteApplicationInitializer.mRetroClient.callCustomFilterApI(type, queryMap, "1");
            requestCall(call, listener);
    }
+4
source share
1 answer

Use Interceptorand convert %26to &:

class RequestInterceptor implements Interceptor {
    @Override
    Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        String stringurl = request.url().toString();
        stringurl = stringurl.replace("%26", "&");

        Request newRequest = new Request.Builder()
                .url(stringurl)
                .build();

        return chain.proceed(newRequest);
    }
}

Install this in your constructor OkHttp:

OkHttpClient client = new OkHttpClient.Builder();
client.addInterceptor(new RequestInterceptor());
+1
source

Source: https://habr.com/ru/post/1695952/


All Articles