Glide - adding header to request

前端 未结 8 1443
北海茫月
北海茫月 2021-02-02 09:25

is there a method to add custom header to request when image is downloaded? I can use volley or okhttp in Glide.

I try add cookie to cookiemanager in okhttpclient, but i

8条回答
  •  天命终不由人
    2021-02-02 10:06

    This is late, I think but I put it here for notes for anyone else facing the issue. Here are my code samples (this is for Glide v4):

    BaseGlideUrlLoader module:

    private static class HeaderedLoader extends BaseGlideUrlLoader {
    
        public static final Headers HEADERS = new LazyHeaders.Builder()
                .addHeader("Referer", UserSingleton.getInstance().getBaseUrl())
                .build();
    
        public HeaderedLoader(ModelLoader concreteLoader) {
            super(concreteLoader);
        }
    
        @Override public boolean handles(@NonNull String model) {
            return true;
        }
    
        @Override protected String getUrl(String model, int width, int height, Options options) {
            return model;
        }
    
        @Override protected Headers getHeaders(String model, int width, int height, Options options) {
            return HEADERS;
        }
    
        public static class Factory implements ModelLoaderFactory {
    
            @Override public @NonNull ModelLoader build(
                    @NonNull MultiModelLoaderFactory multiFactory) {
                return new HeaderedLoader(multiFactory.build(GlideUrl.class, InputStream.class));
            }
    
            @Override public void teardown() { /* nothing to free */ }
        }
    }
    

    Add the HeaderLoader class in the AppGlideModule.

    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
        super.registerComponents(context, glide, registry);
    
        registry.replace(GlideUrl.class, InputStream.class,
                new OkHttpUrlLoader.Factory(CustomOkHttpsClient.getTrustedOkHttpClient()
                ));
    
        // override default loader with one that attaches headers
        registry.replace(String.class, InputStream.class, new HeaderedLoader.Factory());
    }
    

    My solution is based on link provided here https://github.com/TWiStErRob/glide-support/commit/b357427363c28a82495097ec862b82acdf3b4357

    The original issue is discussed here https://github.com/bumptech/glide/issues/471

    Thanks to @TWiStErRob

提交回复
热议问题