Search code examples
javaretrofitokhttpthemoviedb-api

Append query parameter to start of URL using Retrofit


I'm trying to implement the TheMovieDB API using Retrofit and I'm having trouble appending the api key to the beginning of the query. It feels like TheMovieDB is at fault here for having an untraditional way of asking for the api key at the start of the query.

When trying to intercept the request and adding the query parameter, like so, it gets appended to the end of the request, which is not what I want.

    private class WebApiAuthenticator implements RequestInterceptor {
    @Override
    public void intercept(RequestFacade request) {
        if (apiKey != null) {
            request.addEncodedQueryParam(PARAM_API_KEY, apiKey);
        }
    }
}

And the service implementation:

    @GET("/search/multi&query={query}")
    void getSearchResults(@Path("query") String query, Callback<String> callback);

This produces this result:

---> HTTP GET https://api.themoviedb.org/3/search/multi&query=mysearchquery?api_key=thisismyapikey

I want this result:

---> HTTP GET https://api.themoviedb.org/3/search/multi?api_key=thisismyapikey&query=mysearchquery

How do I go about adding my query parameter to the start of the request instead?


Solution

  • I found the solution. Instead of intercepting and adding a query parameter from there, I create a Query Map and always pass my api key to the service in a query map, along with my search query, like so:

    Map<String, String> data = new HashMap<>();
    data.put("api_key", apiKey);
    data.put("query", "avengers");
    movieService.getSearchResults(data, new Callback<String>()
    {
        @Override public void success(final String s, final Response response) {
        System.out.println(s);
        }
    
        @Override public void failure(final RetrofitError error) {
            LOGGER.log(Level.WARNING, error.getResponse().getReason());
        }
    });
    

    And this is the service implementation:

    @GET("/search/multi")
    void getSearchResults(@QueryMap Map<String, String> queries, Callback<String> callback);
    

    This produces the result:

    ---> HTTP GET https://api.themoviedb.org/3/search/multi?api_key=myapikey&query=avengers