0

I had an issue a few weeks ago in a WebView where it wasn't following redirects as a normal browser would. I used the following suggestion given in many SO answers:

String newUrl = response.getFirstHeader("Location").getValue();

but it only gave 1 step of redirection, but not more, which it needed to. I got around it by repeatedly listening for redirects and manually going through each step.

Now I'm using the following code:

HttpClient httpClient = MyApp.getHttpClient();
HttpPost httpPost = new HttpPost(con.getString(R.string.platform_url_getBalances));

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("sid", String.valueOf(sessionKey)));
ResponseHandler<String> responseHandler = new BasicResponseHandler();

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

String response = null;

// Execute HTTP Post Request. Response body returned as a string
response = httpClient.execute(httpPost, responseHandler);

Recently the end-point for the R.string.platform_url_getBalances changed but we put in a 302 redirect to a different URL. It works fine in a browser and on the iPad version of the app but for Android I get org.apache.http.client.HttpResponseException: Not Found.

I find it very strange that Android is such a pain when it comes to redirecting. Why does it behave like this and is there a reasonable way around it?

5
  • That doesn't say why this is the case, and that SO question doesn't have an accepted answer. Also the blog post you linked says "By default DefaultHttpClient will handle redirect automatically", but it doesn't seem to do that.
    – Mike T
    Mar 18, 2013 at 13:10
  • The first link does "say why this is the case" and does have an accepted answer. Mar 18, 2013 at 13:12
  • Didn't notice the first link on the text.
    – Mike T
    Mar 18, 2013 at 13:13
  • If you're willing to post this as an answer, I'll accept it, or I'll just delete the question rather than having unanswered questions floating around.
    – Mike T
    Mar 18, 2013 at 13:20

1 Answer 1

0

Actually, the answer I linked to in my comment is for HttpClient 4.1, near as I can tell, and Android's is older.

My guess is that the equivalent process in Android's version of HttpClient would be do:

  • Create a subclass of DefaultRedirectHandler that overrides isRedirectRequested() as appropriate for your app
  • Create a subclass of DefaultHttpClient and override createRedirectHandler() to return an instance of the subclass you created in the previous step
  • Use your subclass of DefaultHttpClient as a replacement for DefaultHttpClient itself wherever you are creating that instance

Not the answer you're looking for? Browse other questions tagged or ask your own question.