获取“java.net.ProtocolException:服务器重定向次数太多”错误
我正在使用以下代码制作简单的网址请求:
I'm making a simple URL request with code like this:
URL url = new URL(webpage);
URLConnection urlConnection = url.openConnection();
InputStream is = urlConnection.getInputStream();
但是在最后一行,我得到了重定向太多次错误。如果我的网页var是google.com,那么它可以正常工作,但是当我尝试使用我的servlet的URL时,它就失败了。我似乎可以调整重定向遵循的次数(默认为20):
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");
但当我把它调到100时,它肯定需要更长时间才能抛出错误所以我知道它正在努力。但是,我的servlet的URL在(任何)浏览器中工作正常并且在firebug中使用persist选项它似乎只重定向一次。
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.
更多信息在我的servlet上...它在tomcat中运行,并使用'mod-proxy-ajp'在apache前面运行。另外值得注意的是,它使用的是表单身份验证,因此您输入的任何URL都应该将您重定向到登录页面。正如我所说的,这在所有浏览器中都能正常工作,但由于某种原因,重定向不能与Java 6中的URLConnection一起使用。
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?
它显然是在无限循环中重定向,因为你没有维护用户会话。会话通常由cookie支持。在使用 URLConnection
之前,您需要创建一个 CookieManager
。
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();
// ...
参见:
- 使用java.net.URLConnection来触发和处理HTTP请求
- Using java.net.URLConnection to fire and handle HTTP requests