gpt4 book ai didi

java - 在 java 中使用 HttpAsyncClients 实现“即发即忘”

转载 作者:太空宇宙 更新时间:2023-11-04 14:52:31 30 4
gpt4 key购买 nike

我正在尝试在我的应用程序中使用 HTTPAsyncCLient 来实现“即发即忘”。

http://hc.apache.org/httpcomponents-asyncclient-4.0.x/

我正在遵循此处给出的示例: http://hc.apache.org/httpcomponents-asyncclient-4.0.x/httpasyncclient/examples/org/apache/http/examples/nio/client/AsyncClientHttpExchange.java

我的代码如下所示:

           CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
httpclient.start();
HttpGet request = new HttpGet(url);
Future<HttpResponse> future = httpclient.execute(request, null);
/*try {
HttpResponse resp = future.get();
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
String line = null;

while ((line = reader.readLine()) != null) {
sb.append(line);
}
String fr = sb.toString();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
httpclient.close();

如果我取消注释部分,一切正常。但我想做的是“即发即忘”请求。因此,当我注释掉上面的部分时,不会发出 HTTP 请求。知道我做错了什么吗?对于“即发即忘”请求,我该怎么办?

最佳答案

在请求完成之前,您的 httpclient 实例无法关闭。

虽然我不确定,但我建议

// ONCE
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
httpclient.start();


// for every fire and forget request
HttpGet request = new HttpGet(url);
httpclient.execute(request, null);`

在请求之间保持客户端处于 Activity 状态,因此无需调用 close(而是重用实例)

关于java - 在 java 中使用 HttpAsyncClients 实现“即发即忘”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23609954/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com