java - 出现 "java.net.ProtocolException: Server redirected too many times"错误

标签 java url servlets redirect urlconnection

我正在使用如下代码发出一个简单的 URL 请求:

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

但在最后一行,我收到“重定向太多次错误”。如果我的“网页”变量是 google.com,那么它可以正常工作,但是当我尝试使用我的 servlet 的 URL 时,它会失败。看来我可以调整它跟随重定向的次数(默认为 20):

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

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

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

感谢阅读...想法?

最佳答案

它显然是在无限循环中重定向,因为您不维护用户 session 。 session 通常由 cookie 支持。在使用 URLConnection 之前,您需要创建一个 CookieManager

// 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 - 出现 "java.net.ProtocolException: Server redirected too many times"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11022934/

相关文章:

java - 计算餐馆账单的小费和税总额

java - 以编程方式从 LocalizedResource.properties 中读取 key

asp.net-mvc - IIS 无法提供以 .config 结尾的页面

python - URL Dispatch 中路由的多个路径

javascript - 数据库、servlet、json、javascript 和 highchart 饼图

java - Android 运行时异常 :Activity must implement OnFragmentInteractionListener

java - 生成公钥/私钥之前的 RSA 加密强制关闭

javascript - 从 URL 解码 %20 时出现问题

java - 在本地 tomcat 中运行 Web 应用程序失败并出现 LinkageException

java - 无法在 sql 上添加或更新子行