25

I'm using Square's Retrofit library for short-lived network calls. There are a few pieces of data that I include as @Query params on every request. Like so:

@GET("/thingOne.php")
void thingOne(
        @Query("app_version") String appVersion,
        @Query("device_type") String deviceType,
        Callback<Map<String,Object>> callback
);

@GET("/thingTwo.php")
void thingTwo(
        @Query("app_version") String appVersion,
        @Query("device_type") String deviceType,
        Callback<Map<String,Object>> callback
);

It's cumbersome to have to define appVersion and deviceType for every single endpoint outlined in the Interface. Is there a way to set a base set of parameters that should be included with every request? Something similar to how we set a common Authorization Header?

RestAdapter restAdapter = new RestAdapter.Builder()
    .setServer("...")
    .setRequestHeaders(new RequestHeaders() {
        @Override
        public List<Header> get() {
            List<Header> headers = new ArrayList<Header>();
                Header authHeader = new Header(
                    "Authorization", "Bearer " + token);
                headers.add(authHeader);
            }
            return headers;
        }
    })
    .build();
this.service = restAdapter.create(ClientInterface.class);

1 Answer 1

54

You can ensure all requests have these query parameters by adding a custom RequestInterceptor to your RestAdapter

RequestInterceptor requestInterceptor = new RequestInterceptor()
{
    @Override
    public void intercept(RequestFacade request) {
        request.addQueryParam("app_version", "Version 1.x");
        request.addQueryParam("device_type", "Samsung S4");
    }
};

restAdapter.setRequestInterceptor(requestInterceptor)
9
  • 1
    is this what you're talking about? I cant seem to find reference to a class called RequestInterceptor. Or to RequestFacade. And RestAdapter doesn't have a method setRequestInterceptor. Can you provide some more details please? Aug 6, 2013 at 16:01
  • You must have an older version of Retrofit. If you update it to version 1.1.1 you should see them. square.github.io/retrofit/javadoc/retrofit/…
    – Erich
    Aug 6, 2013 at 19:26
  • 1
    @kdubb: How do I do this for Body? I have a POST that accept a json payload. Thanks!
    – dannyroa
    Mar 21, 2014 at 22:39
  • @dannyroa RequestInterceptor allows you to set path params, query params or headers. I assume body was intentionally left out for two reasons: 1) Not all requests allow a body and 2) It would prevent you from setting any other Body
    – Erich
    Mar 21, 2014 at 22:51
  • 2
    how to do this with retrofit 2.0.0.beta1? Sep 30, 2015 at 18:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.