gpt4 book ai didi

java.net.ProtocolException : Server redirected too many times (20)

转载 作者:行者123 更新时间:2023-12-01 14:06:48 28 4
gpt4 key购买 nike

我有这个代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class Demo2 {

public static void main(String[] args) {

try {

String url = "http://www......";

URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setReadTimeout(5000);
conn.addRequestProperty("Accept-Language", "es-ES,es;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
System.out.println("Request URL ... " + url);

boolean redirect = false;

// normally, 3xx is redirect
int status = conn.getResponseCode();

if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}

System.out.println("Response Code ... " + status);

if (redirect) {
System.out.println("Redireccionando...");
// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");

// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
System.out.println("Galletas: " + cookies);

// open the new connnection again
conn = (HttpsURLConnection) new URL(newUrl).openConnection();
conn.setFollowRedirects(true);
conn.setRequestProperty("Cookie", cookies);
conn.addRequestProperty("Accept-Language", "es-ES,es;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");

System.out.println("Redirect to URL : " + newUrl);

}

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();

System.out.println("URL Content... \n" + html.toString());
System.out.println("Done");

} catch (Exception e) {
e.printStackTrace();
}

}

}

结果是:

Request URL ... "http://www.web1.com" Response Code ... 302 Redireccionando... Galletas: 07c18a1bea3520c44535aafeeea31dec07a36313; path=/ Redirect to URL : "https://www.web2.com" java.net.ProtocolException: Server redirected too many times (20) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1635) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) at Demo2.main(Demo2.java:58)

有什么问题吗?我要疯了

最佳答案

我也遇到了同样的问题,这个修复帮助我克服了它。

在调用openConnection();之前使用以下内容:

HttpURLConnection.setFollowRedirects(false);

关于java.net.ProtocolException : Server redirected too many times (20),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18838229/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com