2013-08-31 72 views
2

當我收到HttpServletRequest時,我收到ServletInputStream並逐行讀取請求正文readLine。現在我想知道如果客戶端很慢,我想在超時後返回readLine如何用超時讀取HttpServletRequest數據?

我大概可以安排TimerTask中斷readLine並捕獲InterruptedException。是否有意義?你會建議另一種解決方案來讀取HTTP請求正文超時?

+0

好問題。我多次面對這個問題,但還沒有一個好的解決方案。 – roehrijn

+0

[如何在Java servlet容器上指定Http請求超時參數](http://stackoverflow.com/questions/1414795/how-to-specify-http-request-timeout-parameter-on-java-servlet-容器) – Raedwald

回答

1

您可以實現自己的「緊密」讀取流(小緩衝區大小值,例如,一次8個字節)而不是readLine並在迭代中聲明您的超時。 除此之外,當您阻止IO(在下例中的in.read調用中被阻止)時,您無法做很多事情。當一個線程在IO上被阻塞時,它不會對中斷做出反應。

long timeout = 30000l; //30s 
int bufferSize = 8; 
ByteArrayOutputStream out = new ByteArrayOutputStream(bufferSize); 
try { 
    long start = System.currentTimeMillis(); 
    int byteCount = 0; 
    byte[] buffer = new byte[bufferSize]; 
    int bytesRead = -1; 
    while ((bytesRead = in.read(buffer)) != -1) { 
     out.write(buffer, 0, bytesRead); 
     byteCount += bytesRead; 
     if (System.currentTimeMillis() > start + timeout) { 
      //timed out: get out or throw exception or .... 
     } 
    } 
    out.flush(); 
    return byteCount; 
} ... catch ... finally ....