获取“java.net.ProtocolException:服务器重定向次数过多";错误 [英] Getting "java.net.ProtocolException: Server redirected too many times" Error

查看:67
本文介绍了获取“java.net.ProtocolException:服务器重定向次数过多";错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用如下代码进行简单的 URL 请求:

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

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

但在最后一行,我收到重定向太多次错误".如果我的网页"变量是 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 中运行,并由 apache 使用mod-proxy-ajp"处理.另外值得注意的是,它使用表单身份验证,因此您输入的任何 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.

感谢阅读...想法?

推荐答案

这显然是在无限循环中重定向,因为您没有维护用户会话.会话通常由 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();
// ...

另见:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆