如何使用Retrofit为所有请求定义标题?

我正在寻找一个解决scheme来定义一个唯一的标题在所有请求中使用。 今天,我使用@Header每个请求传递像参数,但我只想定义标题,可以在所有请求中工作,而不需要像parameter passing,例如修改这个标题在我的请求@POST@POST

今天我用这个。 请注意,每个请求@GET我需要定义头为参数。

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

Solutions Collecting From Web of "如何使用Retrofit为所有请求定义标题?"

官方文件:

需要添加到每个请求的头可以使用RequestInterceptor指定。 以下代码创build一个RequestInterceptor,它将为每个请求添加一个User-Agent头。

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

Retrofit 2 ,你需要拦截OkHttp提供的networking层的请求

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

检查这一点 ,它很好地解释了差异。

取决于你的OkHttp库:

 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.1添加标题的解决scheme。 我们需要添加拦截器

  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; } 

现在在你的改造对象中添加这个头在客户端

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

正如其他答案所描述的,您需要一个RequestInterceptor 。 幸运的是,这个接口有一个单一的方法,所以Java 8及以上版本将把它作为一个function接口,让你用lambda实现它。 简单!

例如,如果打包特定的API并且需要每个端点的头文件,那么在构build适配器时可以这样做:

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