HttpGet.abort()/ HttpPost.abort()并不总是立即中止

  • 地址:https://stackoverflow.com/questions/12014673/httpget-abort-httppost-abort-doesnt-always-abort-immediately
  • I’m using Apache HttpComponents 4.2.1 and I’m having trouble getting HttpGet.abort() and HttpPost.abort() to always abort immediately. It works most of the time, but occasionally the connection will block until it times out. I noticed this only happens when I explicitly set a timeout value.
  • Here’s my test code:
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();
				//如果这里不设置timeout参数则不会发生
                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();
}
  • Here’s a sample of the output I get:
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
发布了27 篇原创文章 · 获赞 4 · 访问量 3169

猜你喜欢

转载自blog.csdn.net/u012019209/article/details/102942159