Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Redirect Policy of Volley Framework

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

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.

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.

Edit:

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.

like image 974
Wicket Avatar asked Sep 13 '13 12:09

Wicket


2 Answers

If you don't care about old APIs (< 9) and you just want volley stop following redirects you can do

RequestQueue requestQueue = Volley.newRequestQueue(context, new HurlStack() {
    @Override
    protected HttpURLConnection createConnection(URL url) throws IOException {
        HttpURLConnection connection = super.createConnection(url);
        connection.setInstanceFollowRedirects(false);

        return connection;
    }
});
like image 87
Denis Kniazhev Avatar answered Oct 29 '22 14:10

Denis Kniazhev


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 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);
}
}

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);
    }
}
like image 7
LOG_TAG Avatar answered Oct 29 '22 15:10

LOG_TAG