Retrofit nullable params map

Viewed 1263

I have the interface for retrofit

interface ApiInterface {

    @GET
    Observable<okhttp3.ResponseBody> get(@Url String url,
                                         @HeaderMap Map<String, Object> headerMap,
                                         @QueryMap HashMap<String, String> queryMap );
}

I call this way, and it works perfectly

HashMap<String, String> map = new HashMap<String, String>();
map.put("id","xyz");
apiInterface.get(url,  getHeader(),map)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread());

but when I pass null, it does not work

return apiInterface.get(url,  getHeader(),null)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread());

how pass null for retrofit an interface?

2 Answers

You cannot pass null basically. Two possible solutions.

  1. Either use an empty HashMap<>

          new HashMap<>()
    
  2. Write another api call without that field as below.

interface ApiInterface {

@GET
Observable<okhttp3.ResponseBody> get(@Url String url,
                                     @HeaderMap Map<String, Object> headerMap,
                                     @QueryMap HashMap<String, String> queryMap );

}

interface ApiInterface {

@GET
Observable<okhttp3.ResponseBody> get(@Url String url,
                                     @QueryMap HashMap<String, String> queryMap );

}

You can find more details you can read here: https://github.com/square/retrofit/issues/1488 (It is not my post by the way)

You can pass empty Map if you do not want to send any value to your request param. Use the following code.

HashMap<String, String> map = new HashMap<String, String>();
apiInterface.get(url,  getHeader(),map)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread());
Related