Set maximum number of server redirects followed when using HttpURLConnection
Is there a way to mandate the maximum number of redirects that are followed when using HttpURLConnection?
HttpURLConnection conn = (HttpURLConnection) uri.getURI().toURL();
conn.connect();
I can only see an option to enable/disable redirects
conn.setFollowRedirects(true)
I want to set a max follow of 3 (it seems the default is 20), to preve开发者_开发百科nt exceptions like this:
java.net.ProtocolException: Server redirected too many times (20)
that are caused by circular redirects on some servers.
You can try the http.maxRedirects property:
System.setProperty("http.maxRedirects", "3");
Accroding to HTTP RFC
A user agent should never automatically redirect a request more than 5 times, since such redirections usually indicate an infinite loop.
This forum post explains how to work around this
Why don't you just catch the exception? Changing the threshold number won't change the fact that the function has to report failure to you when it exceeds that number. In fact, lowering the threshold will increase the chances that the function will have to report failure in complex-but-legitimate redirect situations when it would have ultimately succeeded with a higher threshold.
精彩评论