【问题标题】:Exit with grace from DefaultHttpClient从 DefaultHttpClient 优雅地退出
【发布时间】:2017-07-19 18:41:42
【问题描述】:

我们如何退出 HttpClient?没有找到方法。

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

我尝试将执行封闭到一个可关闭的httpresponse,但它没有从类中退出。

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

我也尝试过使用 return 来退出课程。

返回;

【问题讨论】:

  • 为什么要使用已弃用的类?对于已弃用的问题,您不会找到太多帮助
  • 嗯。通常我正在使用的 IDE 会显示它。让我检查一下较新的课程

标签: java http-post httpclient


【解决方案1】:

如果您的 http-client 版本高于 4.3,您可以使用 CloseableHttpClient 代替 HttpClient。它有一个 close() 方法。

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

【讨论】:

  • 谢谢。实际上我采用了这种方法,但它仍然没有退出。虽然我没有使用 defaulthttpclient,因为之前的评论建议不要使用已弃用的类。 CloseableHttpClient 客户端 = HttpClientBuilder.create().build(); HttpPost httpGet = new HttpPost(dataimport_cmd);字符串编码 = DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8")); httpGet.setHeader("授权", "基本" + 编码); client.execute(httpGet); client.close();
  • 实际上你的源代码是正确的并且为我工作。但是,如果我使用像“192.168.3.66:80”这样的 url,其中 192.168.3.66 已关闭,则应用程序正在等待 client.execute() 调用,直到超时。你可能有类似的情况。
猜你喜欢
  • 2011-10-20
  • 2019-04-14
  • 2010-12-16
  • 1970-01-01
  • 2020-11-10
  • 2013-07-21
  • 1970-01-01
  • 1970-01-01
  • 2011-01-21
相关资源
最近更新 更多