首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Retrofit2单例

Retrofit2单例
EN

Stack Overflow用户
提问于 2016-06-16 17:22:00
回答 2查看 3.1K关注 0票数 1

我正在尝试为Retrofit2创建单例实例,它工作得很好。但是,只要我想要动态标题,我就不能这样做。

代码语言:javascript
复制
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.getService().checkExistsTeamName("parameters") ApiManager apiManager =ApiManager.getInstance()

它在这里工作得很好,但是如果我想要添加额外的动态标题,我应该怎么做呢??我被困在这里了

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-06-16 18:39:27

你需要某种依赖注入。试试这段代码。在你打电话给你的服务之前,先打个电话

代码语言:javascript
复制
ApiManager.setHeaders(map of headers);

带有标头值。调用空映射或null来排除它们。

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2016-06-17 11:45:38

按照修改后的文档,如果您想要向特定请求添加标题,您可以这样做,如下所示。

可以使用@Header注释为方法设置静态标头。 @Header(“Cache-Control:max=640000”)@GET(“小部件/列表”) Call widgetList();@Header({ "Accept: application/vnd.github.v3.ull+json“,”username:Retrofit Sample“}) @GET(”用户/{用户名}“)调用getUser(@Path(”用户名“)字符串用户名); 请注意,标题不会相互覆盖。所有同名的标头都将包含在请求中。 可以使用@Header注释动态更新请求头。必须向@头提供相应的参数。如果值为null,则将省略标头。否则,将对值和使用的结果调用toString。 @GET(“用户”)调用getUser(@头(“授权”)字符串授权) 需要添加到每个请求中的标头可以使用OkHttp 拦截器指定。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37865665

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档