更改 Volley 框架的重定向策略 [英] Change Redirect Policy of Volley Framework

查看:15
本文介绍了更改 Volley 框架的重定向策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目中使用 Volley 框架,在该项目中我总是需要自己处理重定向以处理标头.

I am using the Volley framework in a project where I always need to handle the redirects myself to handle the headers.

如何处理重定向现在取决于方法和传输层.我想使用 Volley 的默认值(传输层的自动选择)而不更改任何 Volley 代码.

How redirects are handled depends right now on the method and the transport layer. I would like to use the defaults of Volley (automatic selection of the transport layer) without changing any Volley code.

一个有效的解决方案是始终使用 OkHttp 作为传输层(如 问题和贡献中所述对于 Volley),但我想知道是否有没有额外框架的方法.

A valid solution is to always use OkHttp as a transport layer (as mentioned in Issues and contribution for Volley), but I would like to know if there is a way without an additional framework.

因此,我正在寻找一种干净"的方法来禁用自动重定向处理.

Therefore I am looking for a "clean" way to disable automatic redirect handling.

我更喜欢使用 OkHttp,这样我就不必自己管理在什么 Android 上使用什么版本,但是当想要更改传输层行为时,Itai Hanski 提供的解决方案非常好.

I prefer to use OkHttp so that I don't have to manage what version to use on what Android myself, but the solution provided by Itai Hanski is very good to, when wanting to change the transport layer behavior.

推荐答案

我认为 使用OkHttp作为传输的Volley是最好的解决方案

I think A HttpStack implementation for Volley that uses OkHttp as its transport is the best solution

RequestQueue queue = Volley.newRequestQueue(this);

Network network = new BasicNetwork(new OkHttpStack());
RequestQueue queue = new RequestQueue(new DiskBasedCache(new File(getCacheDir(), "volley")), network);
queue.start();

OkHttpStack 类:

OkHttpStack class:

public class OkHttpStack extends HurlStack {
private final OkHttpClient client;

public OkHttpStack() {
this(new OkHttpClient());
}

public OkHttpStack(OkHttpClient client) {
if (client == null) {
throw new NullPointerException("Client must not be null.");
}
this.client = client;
}

@Override protected HttpURLConnection createConnection(URL url) throws IOException {
return client.open(url);
}
}

更新:如果您使用的是新版本的 okhttp 堆栈,请使用

Update: if you are using new version of okhttp stack then use

public class OkHttpStack extends HurlStack {
    private final OkUrlFactory mFactory;

    public OkHttpStack() {
        this(new OkHttpClient());
    }

    public OkHttpStack(OkHttpClient client) {
        if (client == null) {
            throw new NullPointerException("Client must not be null.");
        }
        mFactory = new OkUrlFactory(client);
    }

    @Override
    protected HttpURLConnection createConnection(URL url) throws IOException {
       return mFactory.open(url);
    }
}

这篇关于更改 Volley 框架的重定向策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆