2015-07-21 41 views
0

我想創建一個名爲close()的方法,當被調用時將釋放我已經調用httpMethod的HttpRequestBase的連接。我的問題是,下面的代碼將在Client 3.x中工作得很好,但它不適用於使用客戶端4.x版本的Android API 21,所以我的問題是如何獲得這個以正確關閉連接Apache客戶端4.x關閉HttpRequestBase

public void close() { 
    ExecutorService es =(ExecutorService) CallableSingleTon.getExecutor(); 
    es.shutdown(); 
    if (null != httpMethod) { 
     httpMethod.releaseConnection(); 
     //postMethod.abort(); 
    } 
    httpMethod = null; 
} 

回答

0

我想這會是這樣的:

try{ 
    CloseableHttpResponse response = httpclient.execute(target, http_req, localContext); 
    response.getEntity().writeTo(System.out); 
    // read the entire stream to end in order to reuse connection 
    EntityUtils.consume(response.getEntity()); 
}finally{ 
    response.close(); 
} 

當HTTP客戶端不再需要,你可以執行httpclient.close();終止所有打開的連接。 客戶端4.x與客戶端3.x完全不同,所以我猜你會需要更多的重構。