2012-04-14 70 views
3

我需要編寫一個基本上只是將每個傳入請求代理到不同主機上相同URL路徑的servlet。下面是我使用Apache Commons Http Client 4.1.3的想法:Proxy Servlet在HttpClient掛起()

@WebServlet("/data/*") 
public class ProxyServlet extends HttpServlet { 

    protected void doGet (HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException { 
    HttpClient client = new DefaultHttpClient(); 
    try { 
     String url = getMappedServiceUrlFromRequest(request); 
     HttpGet get = new HttpGet(url); 
     copyRequestHeaders(request, get); 

     HttpResponse getResp = client.execute(get); 
     response.setStatus(getResp.getStatusLine().getStatusCode()); 
     copyResponseHeaders(getResp, response); 

     HttpEntity entity = getResp.getEntity(); 
     if (entity != null) { 
     OutputStream os = response.getOutputStream(); 
     try { 
      entity.writeTo(os); 
     } finally { 
      try { os.close(); } catch (Exception ignored) { } 
     } 
     } 
    } catch (Exception e) { 
     throw new ServletException(e); 
    } finally { 
     client.getConnectionManager().shutdown(); 
    } 
    } 

    private void getMappedServiceUrlFromRequest (...) 
    private void copyResponseHeaders (...) 
    private void copyRequestHeaders (...) 
} 

這在第一次調用servlet時工作得很好。但是,在第一次之後,該servlet掛起在線client.execute(get)

「HttpClient執行掛起」有很多Google命中,其中大多數建議使用ThreadSafeClientConnManager的實例。試過,可悲的是沒有幫助。

我已經花了好幾個小時來搜索這個問題,但我還沒有發現任何修復它的東西。我真的很感謝任何關於我在這裏做錯了什麼的指針。

+0

您是否嘗試在org.apache.http中啓用調試日誌記錄?那將是我的第一步。 – Alex 2012-04-14 20:29:55

+0

類似的線程值得閱讀:http://stackoverflow.com/questions/4694419/multiple-post-with-httpclient-4-0-3-hanging-randomly – Paul 2012-05-05 22:13:41

回答

0

我建議你這樣做是困難的。只需編寫一個篩選器即可進行重定向。

甚至只是一個TCP端口監聽端口,只是來回複製字節。你根本不需要在代理中使用HTTP協議,除非你正在實現CONNECT命令,在這種情況下,這是你需要理解的唯一HTTP,它的回覆是你需要的唯一HTTP響應瞭解。其他一切都只是字節。