简体   繁体   English

如何在Android中打开HttpClient连接,然后立即关闭

[英]How do I open an HttpClient connection in Android and then close it immediately

I am digging for quite a while and I am wondering how do I open an HttpClient connection in Java (Android) and then close the socket(s) right away without getting CLOSE_WAIT and TIME_WAIT TCP statuses while I am checking network monitoring tools. 我已经研究了很长时间,想知道如何在检查网络监控工具时如何在Java(Android)中打开HttpClient连接,然后立即关闭套接字而不获取CLOSE_WAIT和TIME_WAIT TCP状态。

What I am doing is (Found this solution on stackoverflow site): 我正在做的是(在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();

After I run this code - The PHP file is executed well, I get the response back to TOAST, BUT - when I analyze the networking environment of my mobile device with external network analyzer tool - I see that the connection(s) stay in CLOSE_WAIT or/and TIME_WAIT for about 1 minute and only then they move to CLOSED state. 运行此代码后-PHP文件执行良好,我将响应返回到TOAST,但是-当我使用外部网络分析工具分析移动设备的网络环境时-我发现连接保持在CLOSE_WAIT中或/和TIME_WAIT大约1分钟,然后它们才进入CLOSED状态。

The problem is: I am calling the above function every ~2 to 5 seconds in an infinite loop, which result over time a huge amount of CLOSE_WAITs and TIME_WAITs - which affect the overall performance of my Android app, until it gets stuck and useless ! 问题是:我每隔约2至5秒就会在无限循环中调用上述函数,随着时间的流逝,会产生大量的CLOSE_WAIT和TIME_WAIT-这会影响我的Android应用程序的整体性能,直到卡住和无用!

What I want to do is (And need your answer if possible): I wish to really close the connection RIGHT AWAY after I TOAST the response message without any open sockets. 我想要做的是(如果可能的话,还需要您的回答):我希望在没有任何打开的套接字的情况下,立即举起响应消息后立即关闭连接。 No TIME_WAIT and no CLOSE_WAIT. 没有TIME_WAIT,也没有CLOSE_WAIT。 No left overs at all - close all communication IMMEDIATELY at the split second that I run code that should do so. 完全没有多余的东西-立即运行我应该执行的代码时,立即关闭所有通信。 I don't need the connection anymore until the next iteration of the loop. 在循环的下一次迭代之前,我不再需要连接。

How can I accomplish that ? 我该怎么做? I have in mind that I don't want the application to halt or have poor performance over time, since it should run in a service/stay open forever. 我要记住,我不希望该应用程序随着时间的推移而暂停或性能不佳,因为它应该在永远打开的服务/保持打开状态下运行。

I would really appreciate if you could write simple code that work after I do copy-paste. 如果您能编写简单的代码在复制粘贴后正常工作,我将不胜感激。 I am new to Java and Android, so I will try to figure out the code that you write, so please keep it as simple as possible. 我是Java和Android的新手,因此我将尝试找出您编写的代码,因此请尽可能简化代码。 Thanks a lot ! 非常感谢 !

Question asker. 问问者。

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();
  }

try using HttpURLConnection class. 尝试使用HttpURLConnection类。 refer to following link : http://android-developers.blogspot.de/2011/09/androids-http-clients.html 请参阅以下链接: http : //android-developers.blogspot.de/2011/09/androids-http-clients.html

in the finally clause just call disconnect. 在finally子句中,只需调用disconnect。 Example code .. 示例代码..

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM