Android Volley ImageLoader - 如何使用基本HTTP授权?

lop*_*san 8 android android-volley

我想使用Volley NetworkImageView来从我的REST API加载需要基本HTTP授权的图像.所以我需要向HTTP Request添加标头.

我已经采取了以下方法:

覆盖Request.getHeaders() - 如本问题所述.这将是很好,但问题是,ImageLoader已经new ImageRequest()硬编码,所以我不能把我的Request执行到ImageLoader,它不容易被继承和调整(我需要重新实现方法是使用私有财产).

解决方案是修改Volley库本身(我想避免的).

使用自定义HttpClientStack -描述这里.使用这种方法,我将能够拦截HTTP通信并添加必要的标头.但我认为这不是正确的方法 - 我放弃了Volley自动选择HttpClient(Gingerbread vs. HC和IC).


是否有一些简单的方法来实现这一点,我错过了?

Raf*_*afa 8

我认为HTTP堆栈是要走的路.如果您根据SDK版本进行覆盖,则不会丢失自动HttpClient选择,就像Volley一样.

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
        HurlStack stack = new HurlStack() {
            @Override
            public HttpResponse performRequest(Request<?> request, Map<String, String> headers)
                throws IOException, AuthFailureError {

                headers.putAll(MyApp.getAuthParams());

                return super.performRequest(request, headers);
            }
        };

        requestQueue = Volley.newRequestQueue(getApplicationContext(), stack);

    } else {
        HttpClientStack stack = new HttpClientStack(AndroidHttpClient.newInstance("volley/0")) {
            @Override
            public HttpResponse performRequest(Request<?> request, Map<String, String> headers)
                throws IOException, AuthFailureError {

                headers.putAll(MyApp.getAuthParams());

                return super.performRequest(request, headers);
            }
        };

        requestQueue = Volley.newRequestQueue(getApplicationContext(), stack);
    }
Run Code Online (Sandbox Code Playgroud)

Volley来源(第53行).


njz*_*zk2 6

我也有覆盖getHeaders().到目前为止,我还没有找到更容易做到的方法.

请参阅此示例https://github.com/njzk2/VolleyTwitter/blob/master/src/com/njzk2/twitterbrowser/TokenRequest.java重写请求以包含Authorization标头.

从Volley代码中,如果不是通过覆盖Request对象,我看不到添加自定义头的任何方法.

此外,我不知道如何在给定Volley的结构的情况下轻松添加它,对于Images,ImageRequests是由ImageLoader创建的.

如果我要修改Volley来允许这个,我可以在ImageLoader中使用自定义类扩展ImageRequest.但是ImageLoader中的匿名ImageRequest类使它有点复杂.