我有一个简单的基于 Tomcat 的 Java 应用程序,它充当一种防火墙 - 我从“外部”接收请求,将它们重新路由到“内部”的资源,然后将结果返回到“外部”。 "
这对 GET 工作正常,但我试图为不同的请求添加 POST 函数,但我无法让它工作。 “内部”远程服务器受密码保护,我无法让远程服务器接受身份验证凭据(它们适用于 GET,因此凭据很好。)相反,Tomcat 服务器一遍又一遍地调用 Authenticator,最后失败了。这是我收到的错误:
java.net.ProtocolException: Server redirected too many times (20)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1848)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at com.mystuff.house.server.MyServlet.doPost(MyServlet.java:191)
我确定我在做一些愚蠢的事情,但我看不到它在哪里。这是 servlet doPost() 例程的内容:
URL url = new URL("HTTP", "10.10.1.101", -1, "/myresource");
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection) con;
http.setRequestMethod("POST");
http.setDoOutput(true);
String encoded = String.valueOf(Base64.getEncoder().encode((a.getUsername().concat(":").concat(a.getPassword())).getBytes()));
http.setRequestProperty("Authorization", "Basic "+encoded);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
// Read the POST payload from the front end post, write to back end post
InputStream r = request.getInputStream();
OutputStream os = http.getOutputStream();
int j = 0;
while ((j = r.read()) != -1) {
os.write((byte) j);
}
http.connect();
// Try reading the result from the back end, push it back to the front end
try {
InputStream i = http.getInputStream();
OutputStream o = response.getOutputStream();
// read/write bytes until EOF
j = 0;
while ((j = i.read()) != -1) {
o.write((byte) j);
}
} catch (Exception ex) {
System.out.println("AIEEEE! Error receiving page from HTTP call");
ex.printStackTrace();
}
最佳答案
经过一些调查,这个问题原来是身份验证对我试图在远程服务器上访问的特定 URL 无效。
我曾期望从远程服务器返回 403、401 或 407,但这从未发生,而是发生了“重定向”。因此,如果您尝试从 Java 代码访问受密码保护的 URL,则需要注意这一点。
关于java - 在 Java 中建立的 HTTP 连接因重定向过多而失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40835153/