2016-11-27 31 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,那麼需要注意這一點。