如何使用改造为所有请求定义标头?

2022-09-01 20:13:12

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

今天我用这个。请注意,我需要的每个请求都将 Header 定义为参数。@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());

                }
            }); 

        }

答案 1

公文:

可以使用 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();

答案 2

在 中,您需要在网络层上截获请求,由Retrofit 2OkHttp

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

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


推荐