title: 301/302 Redirect not working in Android (work differently in different versions)
body: <p>When using a URLConnection, the 301 redirect doesn't work, doesn't even show a <code>Location</code> 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 <a href="http://androidforums.com/android-applications/356399-htc-hd-native-browser-ignores-301-redirect.html" rel="nofollow noreferrer">here</a> as well, though in my test it worked in the Android browser. Is there some workaround for this bug in older Android?</p>
  
  <p>I tried:</p>
  
  <pre><code>URLConnection conn = u.openConnection();
  HttpURLConnection conn = (HttpURLConnection) u.openConnection();
  (conn).setInstanceFollowRedirects(true);
  </code></pre>
  
  <p>but it still returns an empty list, except in newer Android.</p>
  
  <p><strong>Update</strong>: 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?</p>
  
  <p><strong>Update</strong>: 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:</p>
  
  <pre><code>        URL u = new URL(_url);
          ...
          int tries = 4;
          int code = 301;
          URLConnection conn = null;
          while (tries &gt; 0 &amp;&amp; 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);
  </code></pre>
  
  <p>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 <code>Connection Reset by Peer</code> 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 <a href="https://stackoverflow.com/questions/2606873/sslexception-hellorequest-followed-by-an-unexpected-handshake-message">comments here</a>, 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?</p>