Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

301/302 Redirect not working in Android (work differently in different versions)

When using a URLConnection, the 301 redirect doesn't work, doesn't even show a Location header, using getHeaderFields(). It is a blank list, except in newer Android (I tested 4.1 and it worked). It looks like something this has been reported in the default browser here as well, though in my test it worked in the Android browser. Is there some workaround for this bug in older Android?

I tried:

URLConnection conn = u.openConnection();
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
(conn).setInstanceFollowRedirects(true);

but it still returns an empty list, except in newer Android.

Update: It may be a related issue, it seems sometimes the URLConnection isn't even sending a request in some cases. (I checked with Wireshark on a pc with emulator). Is there a way to work-around this bug?

Update: I tried testing for 3xx redirect, redirects worked fine, but normal links didn't work with Ian's Cookie Manager. After making sure the setCookies was called directly after openConnection, it works great:

        URL u = new URL(_url);
        ...
        int tries = 4;
        int code = 301;
        URLConnection conn = null;
        while (tries > 0 && code/100 == 3) {
            conn = null;
            conn = u.openConnection();
            _CM.setCookies(conn);
            ((HttpURLConnection)conn).setInstanceFollowRedirects(false);//Required
            code =((HttpURLConnection)conn).getResponseCode();
            if (code/100 == 3) {
                String loc = conn.getHeaderField("Location");
                u = new URL(loc);
            }
        }

        //conn.addRequestProperty("Accept-Encoding", "gzip");

        conn.connect();
        _CM.storeCookies(conn);

The really strange thing is, for newer Android (4.1 emulator) the FollowRedirect line (commented "Required") is not necessary. On older Android (2.2), it gives Connection Reset by Peer error. This was probably the reason my redirect experimental code was failing on 2.2, not 4.1. Any reason for the differences in functionality? According to comments here, redirection https apparently has different behavior depending on the JVM version, could it be that Android's URLConnection/HTTPUrlConnection has changed in different versions as well?

like image 481
NoBugs Avatar asked Oct 13 '12 05:10

NoBugs


1 Answers

Not sure about URLConnection, but I know that HttpClient honors redirects and we use it all the way back to Android 2.1

http://developer.android.com/reference/org/apache/http/client/HttpClient.html

(Based on apache commons HttpClient)

like image 59
Jason Polites Avatar answered Sep 23 '22 23:09

Jason Polites