[英]How do I open an HttpClient connection in Android and then close it immediately
我已經研究了很長時間,想知道如何在檢查網絡監控工具時如何在Java(Android)中打開HttpClient連接,然后立即關閉套接字而不獲取CLOSE_WAIT和TIME_WAIT TCP狀態。
我正在做的是(在stackoverflow網站上找到此解決方案):
String url = "http://example.com/myfile.php";
String result = null;
InputStream is = null;
StringBuilder sb = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
}
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
運行此代碼后-PHP文件執行良好,我將響應返回到TOAST,但是-當我使用外部網絡分析工具分析移動設備的網絡環境時-我發現連接保持在CLOSE_WAIT中或/和TIME_WAIT大約1分鍾,然后它們才進入CLOSED狀態。
問題是:我每隔約2至5秒就會在無限循環中調用上述函數,隨着時間的流逝,會產生大量的CLOSE_WAIT和TIME_WAIT-這會影響我的Android應用程序的整體性能,直到卡住和無用!
我想要做的是(如果可能的話,還需要您的回答):我希望在沒有任何打開的套接字的情況下,立即舉起響應消息后立即關閉連接。 沒有TIME_WAIT,也沒有CLOSE_WAIT。 完全沒有多余的東西-立即運行我應該執行的代碼時,立即關閉所有通信。 在循環的下一次迭代之前,我不再需要連接。
我該怎么做? 我要記住,我不希望該應用程序隨着時間的推移而暫停或性能不佳,因為它應該在永遠打開的服務/保持打開狀態下運行。
如果您能編寫簡單的代碼在復制粘貼后正常工作,我將不勝感激。 我是Java和Android的新手,因此我將嘗試找出您編寫的代碼,因此請盡可能簡化代碼。 非常感謝 !
問問者。
HttpClient httpclient = new HttpClient();
GetMethod httpget = new GetMethod("http://www.myhost.com/");
try {
httpclient.executeMethod(httpget);
Reader reader = new InputStreamReader(httpget.getResponseBodyAsStream(), httpget.getResponseCharSet());
// consume the response entity
} finally {
httpget.releaseConnection();
}
嘗試使用HttpURLConnection類。 請參閱以下鏈接: http : //android-developers.blogspot.de/2011/09/androids-http-clients.html
在finally子句中,只需調用disconnect。 示例代碼..
try {
HttpURLConnection locConn = (HttpURLConnection) locurl.openConnection();
//URL url = locConn.getURL();
locConn.setRequestProperty("Authorization", basicAuth);
locConn.setRequestMethod("GET");
locConn.setRequestProperty("Content-Type", "application/json");
locConn.setRequestProperty("X-Myauthtoken", userCredentials);
retc = locConn.getResponseCode();
reader = new BufferedReader(new InputStreamReader(locConn.getInputStream()));
String sessionK = null;
readVal = reader.readLine();
if (retc == 200) {
}
}catch (...)
{
//handle exception
}finally {
//disconnect here
locConn.disconnect();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.