1

当我尝试从 URL 读取 XML 时出现此错误:java.net.ProtocolException: Server redirected too many times (20)。

我找到了一个解决方案,使用以下行设置 cookie: CookieHandler.setDefault(new ListCookieHandler()); 其中“ListCookieHandler”是我使用请求中的配置定义的类。

但这不起作用。在方法“CookieHandler.setDefault”的 javadoc 中,我发现:“注意:非标准 http 协议处理程序可能会忽略此设置”。我认为这可能是问题所在。我还有另一种解决方案吗?

我的代码是:

int timeout = 120000;
CookieHandler.setDefault(new ListCookieHandler());
HttpURLConnection conn = (HttpURLConnection) new URL("http://...").openConnection();
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
BufferedReader reader = new BufferedReader(new  InputStreamReader(conn.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append(System.getProperty("line.separator"));
}
System.out.println(StringEscapeUtils.unescapeHtml(builder.toString()));

ListCookieHandler 的完整解决方案在链接中:http ://www.java2s.com/Code/Java/JDK-6/UsingCookieHandlerinJava5.htm

4

2 回答 2

0

当我遇到同样的错误时,我使用了:

import java.net.CookieHandler;

import java.net.CookieManager;

CookieHandler.setDefault(new CookieManager());
于 2015-01-25T09:52:11.907 回答
0

调用_openConnection();

HttpURLConnection.setFollowRedirects(false);
于 2019-04-12T10:42:15.060 回答