Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a Header to all request using Retrofit?

Tags:

I'm looking for a solution to define a unique Header to use in all requests. Today I use @Header to each request did pass like parameter but I want define only header that works in all requests without to need pass like a parameter, for example fixing this Header on my requests @GET and @POST

Today I use this. Note that each request @GET I need define Header as parameter.

//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", "[email protected]");         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());                  }             });           } 
like image 389
FernandoPaiva Avatar asked Nov 30 '14 12:11

FernandoPaiva


People also ask

How do I get retrofit response headers?

For Retrofit 2.0's interface, you can do this with Call<T> . @murt the newest code in the Github repository seems to be able to allow you to specify Observable<Result<T>> which gives you response as a parameter, and response has the headers.

How do I add a header in OkHttp?

Adds a header with name and value. Prefer this method for multiply-valued headers like "Cookie". Note that for some headers including Content-Length and Content-Encoding, OkHttp may replace value with a header derived from the request body.

How do I add basic authentication to retrofit?

Approach. You will have to create a Request interceptor ( BasicAuthInterceptor ) which extends Interceptor class of OkHttp library. Then, override intercept function and add your credentials into the request. Generate basic credentials with Credentials class of package OkHttp by using its basic function.


2 Answers

Official document:

Headers that need to be added to every request can be specified using a RequestInterceptor. The following code creates a RequestInterceptor that will add a User-Agent header to every 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(); 
like image 88
daveztong Avatar answered Sep 25 '22 12:09

daveztong


In Retrofit 2, you need to intercept the request on 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 this, it explains the differences very well.

like image 42
Silvia H Avatar answered Sep 24 '22 12:09

Silvia H