0
我有一个简单的基于Tomcat的Java应用程序,用作一种防火墙 - 我从“外部”接收请求,将它们重新路由到“内部”的资源,并将结果返回到“外部”。Java中的HTTP连接失败,导致重定向过多?
这适用于GETs,但我试图为不同的请求添加一个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();
}
这是服务器端的问题,而不是这个客户端代码,除非授权有问题。 – EJP
@EJP它确实证明是身份验证问题。我点击的具体URL需要一个不同的密码。远程服务器从未发回401或403,这正是我所期望的。如果您想将您的评论发布为答案,我很乐意将其标记为正确。 – user1071914