Fresco添加HTTP请求头

项目中用Fresco来管理图片由于服务器图片有不同的版本需要根据客户端的屏幕密度来选择不同的图片共享一份用OkHttp下载图片并添加HTTP头代码。

public class OkHttpNetworkFetcher extends BaseNetworkFetcher{

    private static OkHttpClient mOkClient;

    private Map<String, Call> mCallMap;


    private Context     mAppContext;


    static {
        mOkClient = new OkHttpClient.Builder()
//                .addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
                .build();
    }

    public OkHttpNetworkFetcher(Context mAppContext) {
        this.mAppContext = mAppContext;
    }

    @Override
    public FetchState createFetchState(Consumer consumer, ProducerContext producerContext) {
        return new FetchState(consumer, producerContext);
    }

    @Override
    public void fetch(FetchState fetchState,final Callback callback) {

        final Request request = buildRequest(fetchState);
        Call fetchCall = mOkClient.newCall(request);

        if(mCallMap == null)
            mCallMap = new HashMap<>();

        mCallMap.put(fetchState.getId(), fetchCall);

        final String fetchId = fetchState.getId();

        fetchState.getContext().addCallbacks(new BaseProducerContextCallbacks(){
            @Override
            public void onCancellationRequested() {
                cancelAndRemove(fetchId);
                callback.onCancellation();
            }
        });

        try {
           Response response =  fetchCall.execute();
           ResponseBody    responseBody = response.body();
           callback.onResponse(responseBody.byteStream(), (int) responseBody.contentLength());
        } catch (IOException e) {
            callback.onFailure(e);
        }

        removeCall(fetchId);
    }


    private void removeCall(String id){
        if(mCallMap != null){
            mCallMap.remove(id);
        }
    }

    private void cancelAndRemove(String id){
        if(mCallMap != null){
            Call call = mCallMap.remove(id);
            if(call != null)
                call.cancel();
        }
    }


    private Request buildRequest(FetchState fetchState){
        DisplayMetrics dm  = mAppContext.getResources().getDisplayMetrics();
        int density =  dm.densityDpi;

        return new Request.Builder()
                .addHeader("x-density", String.valueOf(density))
                .get()
                .url(fetchState.getUri().toString())
                .build();

    }


}




《架构文摘》每天一篇架构领域重磅好文,涉及一线互联网公司应用架构(高可用、高性 能、高稳定)、大数据、机器学习等各个热门领域。

原文地址:https://www.cnblogs.com/xwgblog/p/5287140.html