Retrofit2单例实例

时间:2016-06-16 17:22:01

标签: android networking retrofit2

我正在尝试为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(&#34;参数&#34)

这里的工作正常但是如果我想添加额外的额外动态标题我应该怎么做?我被困在这里

2 个答案:

答案 0 :(得分:1)

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

ApiManager.setHeaders(map of headers);
带标题值的

。使用空地图调用或使用null来排除它们。

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

}

答案 1 :(得分:0)

根据改造documentation,如果您要为特定请求添加标头,可以按照以下方式执行此操作。

  

您可以使用@Headers批注为方法设置静态标头。

@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();

@Headers({
    "Accept: application/vnd.github.v3.full+json",
    "User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);
     

请注意,标题不会互相覆盖。所有标题都带有   同名将包含在请求中。

     

请求标头可以使用@Header动态更新   注解。必须为@Header提供相应的参数。   如果该值为null,则将省略标头。否则,toString   将调用值,并使用结果。

@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
     

可以使用指定需要添加到每个请求的标头   一个OkHttp interceptor

相关问题