当我收到HttpServletRequest时我得到ServletInputStream并使用 readLine
逐行读取请求正文。现在我想知道如果客户端非常慢并且我希望 readLine 在超时后返回怎么办。
我也许可以安排一个TimerTask
来中断readLine
并捕获InterruptedException
。是否有意义?您是否会建议另一种解决方案来读取超时的 HTTP 请求正文?
最佳答案
您可以从流中实现您自己的“紧密”读取(较小的 bufferSize 值,例如一次 8 个字节)而不是 readLine 并在迭代中断言超时。 除此之外,当您阻塞 IO 时(在下面示例中的 in.read 调用中被阻塞),您不能做太多事情。当线程在 IO 上被阻塞时,它不会对中断使用react。
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 ....
关于java - 如何读取超时的HttpServletRequest数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18551818/