How to define a header for all queries using Retrofit?

I am looking for a solution to define a unique header for use in all queries. Today I use @Header for every request that passed as a parameter, but I want to define only a header that works in all requests, without having to go as a parameter, for example, fixing this header for my @GET and @POST

Today I use this. Note that each @GET request I need to define the header parameter as.

 //interface @GET("/json.php") void getUsuarioLogin( @Header("Authorization") String token, @QueryMap Map<String, String> params, Callback<JsonElement> response ); //interface @GET("/json.php") void addUsuario( @Header("Authorization") String token, @QueryMap Map<String, String> params, Callback<JsonElement> response ); //using public void getUsuarioLogin(){ Map<String, String> params = new HashMap<String, String>(); params.put("email", "me@mydomain.com"); params.put("senha", ConvertStringToMD5.getMD5("mypassword")); RestAdapter adapter = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.FULL) .setEndpoint(WebServiceURL.getBaseWebServiceURL()) .build(); UsuarioListener listener = adapter.create(UsuarioListener.class); listener.getUsuarioLogin( //header "Basic " + BasicAuthenticationRest.getBasicAuthentication(), params, new Callback<JsonElement>() { @Override public void success(JsonElement arg0, Response arg1) { Log.i("Usuario:", arg0.toString() + ""); } @Override public void failure(RetrofitError arg0) { Log.e("ERROR:", arg0.getLocalizedMessage()); } }); } //using public void addUsuario(){ Map<String, String> params = new HashMap<String, String>(); params.put("name", "Fernando"); params.put("lastName", "Paiva"); RestAdapter adapter = new RestAdapter.Builder() .setLogLevel(RestAdapter.LogLevel.FULL) .setEndpoint(WebServiceURL.getBaseWebServiceURL()) .build(); UsuarioListener listener = adapter.create(UsuarioListener.class); listener.addUsuario( //header "Basic " + BasicAuthenticationRest.getBasicAuthentication(), params, new Callback<JsonElement>() { @Override public void success(JsonElement arg0, Response arg1) { Log.i("Usuario:", arg0.toString() + ""); } @Override public void failure(RetrofitError arg0) { Log.e("ERROR:", arg0.getLocalizedMessage()); } }); } 
+21
java android rest retrofit
Nov 30 '14 at 12:35
source share
5 answers

Official document:

The headers to be added to each request can be specified using the RequestInterceptor. The following code creates a RequestInterceptor that will add a User-Agent header for each request.

 RequestInterceptor requestInterceptor = new RequestInterceptor() { @Override public void intercept(RequestFacade request) { request.addHeader("User-Agent", "Retrofit-Sample-App"); } }; RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint("https://api.github.com") .setRequestInterceptor(requestInterceptor) .build(); 
+31
Nov 30 '14 at 13:04
source share

In Retrofit 2 you need to intercept the request at the network layer provided by OkHttp

 OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request original = chain.request(); Request request = original.newBuilder() .header("User-Agent", "Your-App-Name") .header("Accept", "application/vnd.yourapi.v1.full+json") .method(original.method(), original.body()) .build(); return chain.proceed(request); } } OkHttpClient client = httpClient.build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(API_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); 

Check out this one , it explains the differences very well.

+12
Apr 02 '16 at 3:36 on
source share

Depending on your OkHttp lib:

 OkHttpClient httpClient = new OkHttpClient(); httpClient.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder().addHeader("User-Agent", System.getProperty("http.agent")).build(); return chain.proceed(request); } }); Retrofit retrofit = new Retrofit.Builder() .baseUrl(API_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(httpClient) .build(); 
+2
May 11 '16 at 7:37
source share

Here's the solution for adding a header using modification 2.1. We need to add an interceptor.

  public OkHttpClient getHeader(final String authorizationValue ) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient okClient = new OkHttpClient.Builder() .addInterceptor(interceptor) .addNetworkInterceptor( new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request request = null; if (authorizationValue != null) { Log.d("--Authorization-- ", authorizationValue); Request original = chain.request(); // Request customization: add request headers Request.Builder requestBuilder = original.newBuilder() .addHeader("Authorization", authorizationValue); request = requestBuilder.build(); } return chain.proceed(request); } }) .build(); return okClient; } 

Now in your modified object add this header in the client

 Retrofit retrofit = new Retrofit.Builder() .baseUrl(url) .client(getHeader(authorizationValue)) .addConverterFactory(GsonConverterFactory.create()) .build(); 
0
Aug 23 '16 at 10:53 on
source share

As the other answers said, you will need a RequestInterceptor . Fortunately, this interface has a single method, so Java 8 and above will consider it as a functional interface and allow it to be implemented using lambda. Plain!

For example, if you wrap a specific API and need a header for each endpoint, you can do this when creating the adapter:

 RestAdapter whatever = new RestAdapter.Builder().setEndpoint(endpoint) .setRequestInterceptor(r -> r.addHeader("X-Special-Vendor-Header", "2.0.0")) .build() 
0
Nov 17 '17 at 19:57
source share



All Articles