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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27213291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:24:41  来源:igfitidea点击:

How to define a Header to all request using Retrofit?

javaandroidresthttp-headersretrofit

提问by FernandoPaiva

I'm looking for a solution to define a unique Header to use in all requests. Today I use @Headerto 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 @GETand @POST

我正在寻找一种解决方案来定义要在所有请求中使用的唯一 Header。今天,我习惯于@Header每个请求都传递类似参数,但我只想定义适用于所有请求的标头,而不需要像参数一样传递,例如在我的请求中修复这个标头@GET@POST

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

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

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

                }
            }); 

        }

回答by daveztong

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,它将为每个请求添加一个 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();

回答by Silvia H

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

Retrofit 2,需要拦截网络层提供的请求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.

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

回答by jobbert

Depending on your OkHttp lib:

取决于您的 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();

回答by Mr. Mastodon Farm

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!

正如其他答案所描述的那样,您需要一个RequestInterceptor. 幸运的是,此接口只有一个方法,因此 Java 8 及更高版本会将其视为函数式接口,并让您使用 lambda 来实现它。简单的!

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:

例如,如果您要包装特定的 API 并且需要每个端点的标头,则可以在构建适配器时执行此操作:

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

回答by swetabh suman

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

这是使用改造 2.1 添加标题的解决方案。我们需要添加拦截器

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