Is there a way to set a base request parameter to be included in every request made with Square's Retrofit library?

StackOverflow https://stackoverflow.com/questions/17580223

Question

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);
Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top