• Post Reply Bookmark Topic Watch Topic
  • New Topic

HttpURLConnection and Redirects  RSS feed

 
Andy Wilson
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an app that executes a Get method to a web server via HttpURLConnection. It works fine on the test server, but fails on the live server. Investigation shows that the live server is doing a rediect (status 302 gets returned). How do I get HttpURLConnection to follow the redirect: I've tried setting the instanceFollowRedirects to true, to no avail.

Code snippet is:

URL url = new URL("<<....>>");

HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.setInstanceFollowRedirects(true);
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));

.....

I'm sure that this must be a common issue, but can't find any obvious solutions.

Cheers,
Andy Wilson
 
Andy Wilson
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK - first I don't think that I should be setting connection parameters after it's been opened! Even so, the follow redirects seems to default to true, so why doesn't it work? I know that the rediect doesn't require further intervention because I can use the Firefox poster utility to quite happily hit the URL.
 
Aneesh Vijendran
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,


You don't need to travel this far to do this simple stuff. I would ask you to have a look into Apache HttpClient:

A Sample Snippet:



http://hc.apache.org/httpclient-3.x/features.html

Cheers
Aneesh
 
Henry Wong
author
Sheriff
Posts: 23028
120
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andy Wilson wrote:Even so, the follow redirects seems to default to true, so why doesn't it work?


Yeah, that doesn't make sense. The follow redirect is default to true, and should not need to be set. And I am assuming that you are not using a socket factory that clear it either.

Henry
 
Andy Wilson
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No I'm clearing it (I've tested it to make sure that it's true).
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!