获取"java.net.ProtocolException:服务器重定向次数太多"错误

rjc*_*arr 32 java url redirect servlets urlconnection

我正在使用这样的代码创建一个简单的URL请求:

URL url = new URL(webpage);
URLConnection urlConnection = url.openConnection();
InputStream is = urlConnection.getInputStream();
Run Code Online (Sandbox Code Playgroud)

但是在最后一行,我得到了"重定向太多次错误".如果我的"网页"var是google.com,那么它可以正常工作,但是当我尝试使用我的servlet的URL时,它就失败了.我似乎可以通过以下方式调整重定向后的次数(默认为20):

System.setProperty("http.maxRedirects", "100");
Run Code Online (Sandbox Code Playgroud)

但是当我把它调到100时,它肯定需要更长的时间来抛出错误所以我知道它正在尝试.但是,我的servlet的URL在(任何)浏览器中工作正常,并使用firebug中的"persist"选项,它似乎只重定向一次.

关于我的servlet的更多信息...它在tomcat中运行,并使用'mod-proxy-ajp'在apache前面运行.另外值得注意的是,它使用的是表单身份验证,因此您输入的任何URL都应该将您重定向到登录页面.正如我所说,这在所有浏览器中都能正常工作,但由于某些原因,重定向不适用于Java 6中的URLConnection.

感谢阅读...想法?

Bal*_*usC 44

它显然是在无限循环中重定向,因为您不维护用户会话.会话通常由cookie支持.您需要CookieManager在使用之前创建一个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();
// ...
Run Code Online (Sandbox Code Playgroud)

也可以看看:

  • 正如dbf在评论中所说,问题确实与cookie有关.您在此处发布的内容基本上是我使用的解决方案,因此我将此标记为已接受的答案.希望我能帮助dbf.:) (2认同)

小智 5

Duse,我添加了以下几行:

java.net.CookieManager cm = new java.net.CookieManager();
java.net.CookieHandler.setDefault(cm);
Run Code Online (Sandbox Code Playgroud)

请参阅以下示例:

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));
Run Code Online (Sandbox Code Playgroud)