5

我正在使用 Apache HttpComponents 4.2.1,但无法让 HttpGet.abort() 和 HttpPost.abort() 始终立即中止。它大部分时间都可以工作,但偶尔连接会阻塞,直到超时。我注意到这只发生在我明确设置超时值时。

这是我的测试代码:

public static void main(String[] args) throws Exception {
    for (int i = 0; i < 10; i++) {
        testAbort();
    }
}

public static void testAbort() throws Exception {
    String urlString = "http://slow.website.com";

    final HttpGet httpGet = new HttpGet(urlString);

    Runnable runnable = new Runnable() {
        public void run() {
            try {
                HttpClient httpClient = new DefaultHttpClient();

                HttpParams httpParams = httpClient.getParams();

                HttpConnectionParams.setConnectionTimeout(httpParams, 10000); // issue doesn't occur if I comment this line

                httpClient.execute(httpGet);
            } 
            catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    };

    Thread t = new Thread(runnable);

    t.start();

    Thread.sleep(100);

    httpGet.abort();
}

这是我得到的输出示例:

Request already aborted
Request already aborted
Request already aborted
Socket closed
Request already aborted
Connection has been shut down
Socket closed
Socket closed
Connect to slow.website.com:80 timed out
Connect to www.website.com:80 timed out

您可能需要增加迭代次数或调整 Thread.sleep() 值才能看到问题发生。

根据 HttpComponent 文档,“当一个 HTTP 请求被中止时,它在 I/O 操作中被阻塞的执行线程通过抛出一个 InterruptedIOException 来保证解除阻塞”(链接

我正在运行 Mac OS X 10.8(Java 版本 1.6.0_29)。

任何想法可能是什么问题?

4

0 回答 0