Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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); 
like image 771
Alfie Hanssen Avatar asked Jul 10 '13 20:07

Alfie Hanssen


People also ask

How do you add parameters in GET request?

To do http get request with parameters in Angular, we can make use of params options argument in HttpClient. get() method. Using the params property we can pass parameters to the HTTP get request. Either we can pass HttpParams or an object which contains key value pairs of parameters.

How long can a request parameter be?

The average request size ranges from 512-1024 Kb. In fact, there should be no more than 5 parameters in one request, otherwise, each of them will be difficult to control from the server and browser side. If you need to transfer a large amount of information, using the POST method is recommended.


1 Answers

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) 
like image 61
Erich Avatar answered Sep 20 '22 01:09

Erich