我正在尝试为Retrofit2创建单例实例,它工作正常。但是,一旦我想创建动态标头,就无法这样做。

public class ApiManager {


    public final static String BASE_URL = "URL";



    private static ApiManager instance =null;
    private ApiModule apiModule;

    public interface ApiModule {


        @GET("exists")
        Call<ServerStatus> checkExistsTeamName(@Path("teamName") String teamName);


    }


    private ApiManager(){
        final TimeZone tz = TimeZone.getDefault();
        OkHttpClient client = new OkHttpClient();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        try {
            client.interceptors().add(new Interceptor() {
                @Override
                public com.squareup.okhttp.Response intercept(Interceptor.Chain chain) throws
                        IOException {

                    Request original = chain.request();
                    Request request = original.newBuilder()
                            .header("X-API-Version", "1")
                            .header("X-USER-TIMEZONE", tz.getID())
                            .method(original.method(), original.body())
                            .build();


                    return chain.proceed(request);

                }
            });
        }catch (Exception e){

        }
        client.interceptors().add(interceptor);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        apiModule = retrofit.create(ApiModule.class);
    }





    public static ApiManager getInstance() {
        if(instance == null) {
            instance = new ApiManager();
        }
        return instance;
    }




    public ApiModule getService() {
        return apiModule;
    }

    public ApiModule getService(String token){
        return apiModule;
    }




}


在其他活动中,我可以致电进行改造。

ApiManager apiManager = ApiManager.getInstance();
apiManager.getService()。checkExistsTeamName(“ parameters”)

哪个在这里可以正常工作,但是如果我想添加额外的动态标题,我该怎么办呢?我被困在这里

最佳答案

您需要某种依赖注入。试试这个代码。在致电服务之前,请致电

ApiManager.setHeaders(map of headers);


与标头值。使用空的地图调用或将其排除以将其排除。

public class ApiManager {
    public final static String BASE_URL = "URL";
    private static ApiManager instance =null;
    private ApiModule apiModule;

    public interface ApiModule {
       @GET("exists")
       Call<ServerStatus> checkExistsTeamName(@Path("teamName") String
       teamName);
    }

private static Map<String, String> headers = new HashMap<>();

public static void setHeaders(Map<String, String> headers) {
    ApiManager.headers = headers;
}

private ApiManager(){
    final TimeZone tz = TimeZone.getDefault();
    OkHttpClient client = new OkHttpClient();
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    try {
        client.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws
                    IOException {

                Request original = chain.request();
                Request.Builder builder = original.newBuilder()
                        .header("X-API-Version", "1")
                        .header("X-USER-TIMEZONE", tz.getID())
                        .method(original.method(), original.body());

                if(headers != null) {
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        builder.header(entry.getKey(), entry.getValue());
                    }
                }

                Request request = builder.build();

                return chain.proceed(request);

            }
        });
    }catch (Exception e){

    }
    client.interceptors().add(interceptor);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();

    apiModule = retrofit.create(ApiModule.class);
}





public static ApiManager getInstance() {
    if(instance == null) {
        instance = new ApiManager();
    }
    return instance;
}




public ApiModule getService() {
    return apiModule;
}

public ApiModule getService(String token){
    return apiModule;
}


}

07-24 13:55