我正在使用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来解除阻塞”(link)
我正在运行Mac OS X 10.8(Java版本1.6.0_29)。
任何想法可能是什么问题?