【问题标题】:How to read HttpServletRequest data with timeout?如何读取超时的 HttpServletRequest 数据?
【发布时间】:2013-08-31 19:08:28
【问题描述】:

当我收到HttpServletRequest 时,我会收到ServletInputStream 并逐行读取带有readLine 的请求正文。现在我想知道如果客户端非常慢并且我希望readLine 在超时后返回怎么办。

我可以安排一个TimerTask 来中断readLine 并捕捉InterruptedException。是否有意义?你会建议另一种解决方案来读取超时的 HTTP 请求正文吗?

【问题讨论】:

标签: java servlets httprequest inputstream


【解决方案1】:

您可以从流中实现自己的“紧密”读取(小的 bufferSize 值,例如一次 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 ....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2017-10-26
    • 2018-11-17
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多