【问题标题】:How do I open an HttpClient connection in Android and then close it immediately如何在 Android 中打开 HttpClient 连接,然后立即关闭它
【发布时间】:2015-07-22 10:37:28
【问题描述】:

我已经挖掘了很长一段时间,我想知道如何在 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 应用程序的整体性能,直到它卡住并且无用!

我想要做的是(如果可能的话需要你的回答): 我希望在没有任何打开的套接字的情况下 TOAST 响应消息后立即关闭连接。没有 TIME_WAIT 也没有 CLOSE_WAIT。完全没有剩余 - 在我运行应该这样做的代码的瞬间关闭所有通信。在循环的下一次迭代之前,我不再需要连接。

我怎样才能做到这一点? 我记得我不希望应用程序随着时间的推移停止或性能不佳,因为它应该在服务中运行/永远保持打开状态。

如果您能在我完成复制粘贴后编写简单的代码,我将不胜感激。 我是 Java 和 Android 的新手,所以我会试着弄清楚你写的代码,所以请尽可能简单。非常感谢!

提问者。

【问题讨论】:

  • 你试过了吗:httpClient.getConnectionManager().shutdown();
  • 嗨菲利普,是的,我做到了。我尝试了 .shutdown 并尝试了 .close() - 全部留下 CLOSE_WAIT/TIME_WAIT 的痕迹大约一分钟或更长时间。由于我需要每隔几秒钟循环运行一次此代码 - 我遇到了上面提到的问题。

标签: java android sockets httpclient


【解决方案1】:

尝试使用 HttpURLConnection 类。请参考以下链接: http://android-developers.blogspot.de/2011/09/androids-http-clients.html

在 finally 子句中调用断开连接。示例代码..

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

【讨论】:

  • 这段代码看起来很有趣!它只在 CLOSE_WAIT 中保持一个连接打开。一旦我在我的循环中再次运行它 - 它会关闭以前的连接。重新打开它并立即将其移动到具有新时间戳的新 CLOSE_WAIT。最重要的是之前的CLOSE_WAIT变成了CLOSE,所以不存在重复的CLOSE_WAIT来重载app。然而,问题是,我看不到单个 CLOSE_WAIT 最终何时变为 CLOSE。它始终保持打开状态。有没有办法杀死最后一个 CLOSE_WAIT ?谢谢!
  • 如果您在 Android 开发者网站上阅读了有关断开连接的方法,我认为它会解决您的问题...
【解决方案2】:
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();
  }

【讨论】:

  • 嗨,亲爱的家伙,很遗憾,我什至无法编译您提供的代码。 Eclipse 不识别它作为建议其他方法导入。我正在尝试在 Android 开发者论坛中阅读有关 httpclient 的信息,它说“此接口在 API 级别 22 中已弃用”。对于httpclient。你有其他选择吗?
猜你喜欢
  • 2017-11-21
  • 2016-03-19
  • 2016-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多