Java HttpClient 发送请求,无需等待响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18628711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HttpClient sends request and no wait for the response
提问by user2749336
I am trying to make a java controller class that accomplishes the following tasks:
我正在尝试制作一个完成以下任务的 java 控制器类:
when it receives one request , it willprocess on it.
when the process is done and before the return statement , I instanited one Httpclient and try to make one request exactly like current one and post it to another server.
当它收到一个请求时,它会对其进行处理。
当该过程完成并在返回语句之前,我实例化了一个 Httpclient 并尝试发出一个与当前请求完全相同的请求并将其发布到另一台服务器。
I already done with the tasks. but I wonder what happens here : (below)
我已经完成了任务。但我想知道这里发生了什么:(如下)
HttpResponse response=client.execute(post);// will the program blocks here ?
As I search the internet , it seems to be true that the program blocks and that's not what I want.
当我在互联网上搜索时,程序阻塞似乎是真的,这不是我想要的。
I also read about the asynchronise things , but it seems to process the response in the end which may still takes some time. ( not quite sure )
我还阅读了有关异步事物的信息,但似乎最终会处理响应,这可能仍需要一些时间。(不太确定)
How could I just send the request and cares nothing about the response. Is it possible ?
我怎么能只发送请求而不关心响应。是否可以 ?
Sorry if i get everything messed up . It will be really kind of you to shed some light on my mind or just offer some advice on this topic. Thanks.
对不起,如果我把一切都搞砸了。如果您能对我的想法有所了解,或者只是就这个主题提供一些建议,那将是非常友好的。谢谢。
回答by Qben
Even though I find the question a bit confusing I think what you are after is a asynchronous Http call. This way you can choose if you want to read the response or not. There is a good post on this forum on how to write this.
尽管我觉得这个问题有点令人困惑,但我认为您所追求的是异步 Http 调用。通过这种方式,您可以选择是否要阅读回复。这个论坛上有一篇关于如何写这个的好帖子。
How do you create an asynchronous HTTP request in JAVA?
Also, this might be of interest http://hc.apache.org/httpcomponents-client-ga/for future references.
此外,这可能对http://hc.apache.org/httpcomponents-client-ga/感兴趣以供将来参考。
回答by William Gaul
My favorite asynchronous HTTP library for Java is AsyncHttpClient.
我最喜欢的 Java 异步 HTTP 库是AsyncHttpClient。
If you don't care about processing the response, then you can just do:
如果您不关心处理响应,那么您可以这样做:
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
Future<Response> f = asyncHttpClient.preparePost("http://www.myurlhere.com/").execute();
and then just forget about it.
然后就忘了它。