2017-07-19 147 views
0

如何從HttpClient退出?沒有找到方法。從DefaultHttpClient以優雅退出

HttpClient Client = new DefaultHttpClient(); 
String userpass = usr + ":" + pwd; 

HttpPost httpGet = new HttpPost(dataimport_cmd); 
String encoding = DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8")); 
httpGet.setHeader("Authorization", "Basic " + encoding); 

Client.execute(httpGet); 

我試着將執行封閉到一個closeablehttpresponse,但它沒有從類中退出。

CloseableHttpResponse response = (CloseableHttpResponse) 
Client.execute(httpGet); 
response.close(); 

我試過使用返回也退出類。

return;

+0

你爲什麼使用已棄用的類?對於已棄用的問題,您不會找到太多幫助 –

+0

hmmmm。通常我使用的IDE會指示它。讓我檢查一下新班 – user3286012

回答

0

如果您的http客戶端版本高於4.3,您可以使用CloseableHttpClient而不是HttpClient。它有一個close()方法。

CloseableHttpClient client = new DefaultHttpClient(); 
... 
client.close(); 
+0

謝謝。其實我採用這種方法,但它仍然沒有退出。雖然我沒有使用defaulthttpclient,因爲之前的評論建議不要使用depracated類。 CloseableHttpClient客戶端= HttpClientBuilder.create()。build(); \t HttpPost httpGet = new HttpPost(dataimport_cmd); \t String encoding = DatatypeConverter.printBase64Binary(userpass.getBytes(「UTF-8」)); \t httpGet.setHeader(「Authorization」,「Basic」+ encoding); \t \t client.execute(httpGet); \t \t client.close(); – user3286012

+0

其實你的源代碼是正確的,爲我工作。但是,如果我使用像「http://192.168.3.66:80」這樣的URL,其中192.168.3.66處於關閉狀態,則應用程序正在等待client.execute()調用,直到超時。你可能有類似的情況。 – taner