2016-11-27 68 views
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(); 
     } 
+0

这是服务器端的问题,而不是这个客户端代码,除非授权有问题。 – EJP

+0

@EJP它确实证明是身份验证问题。我点击的具体URL需要一个不同的密码。远程服务器从未发回401或403,这正是我所期望的。如果您想将您的评论发布为答案,我很乐意将其标记为正确。 – user1071914

回答

0

与此问题,经过一番调查,原来是该认证是无效的,我是想打遥控器上的特定网址服务器。

我原本以为从远程服务器得到403,401或407回来,但从未发生过,而是发生了这种“重定向”。因此,如果您试图从Java代码访问受密码保护的URL,那么需要注意这一点。