35

I'm making a simple URL request with code like this:

URL url = new URL(webpage);
URLConnection urlConnection = url.openConnection();
InputStream is = urlConnection.getInputStream();

But on that last line, I'm getting the "redirected too many times error". If my "webpage" var is, say, google.com then it works fine, but when I try to use my servlet's URL then it fails. It seems I can adjust the number of times it follows the redirects (default is 20) with this:

System.setProperty("http.maxRedirects", "100");

But when I crank it up to, say, 100 it definitely takes longer to throw the error so I know it is trying. However, the URL to my servlet works fine in (any) browser and using the "persist" option in firebug it seems to only be redirecting once.

A bit more info on my servlet ... it is running in tomcat and fronted by apache using 'mod-proxy-ajp'. Also of note, it is using form authentication so any URL you enter should redirect you to the login page. As I said, this works correctly in all browsers, but for some reason the redirect isn't working with the URLConnection in Java 6.

Thanks for reading ... ideas?

rjcarr
  • 1,932
  • 2
  • 20
  • 29
  • Are you calling yourself and directing that call itself? e.g. Infinite recusion? – bluevector Jun 13 '12 at 20:40
  • 7
    Could you try to open this page in browser with disabled cookies? – dbf Jun 13 '12 at 20:41
  • I take it webpage != (servlet's URL which contains `URL url = new URL(webpage); URLConnection urlConnection = url.openConnection(); InputStream is = urlConnection.getInputStream();`) – Samy Vilar Jun 13 '12 at 20:42
  • jonnyGold: do you mean localhost or something? no, the url is external; samy: not sure what you're asking; dbf: bingo! this is it, thanks! – rjcarr Jun 13 '12 at 20:55
  • Im glad you got it we were just making sure your script wasn't calling itself again and again, but Im glad you got it working. – Samy Vilar Jun 13 '12 at 22:48

4 Answers4

49

It's apparently redirecting in an infinite loop because you don't maintain the user session. The session is usually backed by a cookie. You need to create a CookieManager before you use URLConnection.

// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...

connection = new URL(url).openConnection();
// ...

connection = new URL(url).openConnection();
// ...

See also:

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • 2
    As dbf said in the comments, the problem was indeed related to cookies. What you posted here is essentially the solution I used so I'll mark this as the accepted answer. Wish I could give an assist to dbf. :) – rjcarr Jun 14 '12 at 17:33
5

Duse, I have add this lines:

java.net.CookieManager cm = new java.net.CookieManager();
java.net.CookieHandler.setDefault(cm);

See this example:

java.net.CookieManager cm = new java.net.CookieManager();
java.net.CookieHandler.setDefault(cm);
String buf="";
dk = new DAKABrowser(input.getText());
try {
    URL url = new URL(dk.toURL(input.getText()));
    DataInputStream dis = new DataInputStream(url.openStream());
    String inputLine;
    while ((inputLine = dis.readLine()) != null) {
        buf+=inputLine;
        output.append(inputLine+"\n");
    }
    dis.close();
} 
catch (MalformedURLException me) {
    System.out.println("MalformedURLException: " + me);
}
catch (IOException ioe) {
    System.out.println("IOException: " + ioe);
}
titulo.setText(dk.getTitle(buf));
Anders R. Bystrup
  • 14,996
  • 10
  • 58
  • 53
Daniel Kennedy
  • 670
  • 11
  • 18
1

I was using Jenkins on Tomcat6 on a unix environment and got this bug. For some reason, upgrading to Java7 solved it. I'd be interested to know exactly why that fixed it.

user64141
  • 4,719
  • 4
  • 33
  • 30
0

I had faced the same problem and it took considerable amount of time to understand the problem. So to summarize the problem was in mismatch of headers.

Consider below being my Resource

  @GET
  @Path("booksMasterData")
  @Produces(Array(core.MediaType.APPLICATION_JSON))
  def booksMasterData(@QueryParam("stockStatus") stockStatus : String): Response = {
 // some logic here to get the books and send it back
    }

And here is client code, which was trying to connect to my above resource

ClientResponse clientResponse = restClient.resource("http://localhost:8080/booksService").path("rest").path("catalogue").path("booksMasterData").accept("application/boks-master-data+json").get(ClientResponse.class);

And the error was coming on exactly above line.

What was the problem?

My Resource was using

"application/json"

in

@Produces annotation

and my client was using

accept("application/boks-master-data+json") and this was the problem.

It took me long to find out this as the error was no where related. Break through was when I tried to access my resource in postman with

Accept-> "application/json" header

it worked fine, however with

Accept-> "application/boks-master-data+json" header it doesnt.

And again, even Postman was not giving me proper error. The error was too generic. Please see the below image for reference. Generic error message

Sanjay Bharwani
  • 1,687
  • 21
  • 22