How to define a Header to all request using Retrof

2019-03-14 11:53发布

问题:

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", "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());

                }
            }); 

        }

回答1:

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();


回答2:

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.



回答3:

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();


回答4:

As the other answers have described, you need a RequestInterceptor. Luckily, this interface has a single method, so Java 8 and above will treat it as a functional interface and let you implement it with a lambda. Simple!

For example, if you're wrapping a specific API and need a header for each endpoint, you might do this when you build your adapter:

RestAdapter whatever = new RestAdapter.Builder().setEndpoint(endpoint)
                                                .setRequestInterceptor(r -> r.addHeader("X-Special-Vendor-Header", "2.0.0"))
                                                .build()


回答5:

Here's the solution for adding header using retrofit 2.1. We need to add 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 retrofit object add this header in the client

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(getHeader(authorizationValue))
                .addConverterFactory(GsonConverterFactory.create())
                .build();