11

How to send asynchronous HTTP GET/POST request in java without waiting/reading response ?I don't want to use any third party libraries ..

pavan
  • 3,225
  • 3
  • 25
  • 29

3 Answers3

5

If you're not interested in reading the response at all you can just use URL.openStream() to create a connection and then immediately close the socket (or ignore it and let it time out, if you feel like being mean to the server). This isn't strictly asynchronous, but it will be quite a bit faster than any approach that relies upon fetching and parsing the server's response.

This can of course be made asynchronous by offloading the openStream() calls to another thread, either manually or by using the utilities available in java.util.concurrent.

aroth
  • 54,026
  • 20
  • 135
  • 176
  • URL.openConnection() is not sending HTTP request to the server.this is the code **URL url = new URL("http://localhost/"); URLConnection myURLConnection = url.openConnection(); myURLConnection.connect();** and I've seen apache access logs and it is not getting the request. – pavan Jan 24 '12 at 07:32
  • 2
    @pavan - Ah, my mistake, the API to use is actually `openStream()`, not `openConnection()`. `openConnection()` prepares a connection object, but does not actually establish a connection to the server. `openStream()` establishes the connection and returns the `InputStream` associated with it, which you are then free to read or close or ignore. I'll edit my answer accordingly. – aroth Jan 24 '12 at 11:18
1

java.util.concurrent can be used .

If you interested is using third party libraries then you might want to take a look at

Async Http Client

Sandeep Pathak
  • 10,567
  • 8
  • 45
  • 57
0

I would suggest using something like the Jetty HttpClient if you don't mind adding the Jetty libraries to your app. Here's a good example from Jetty's wiki page http://wiki.eclipse.org/Jetty/Tutorial/HttpClient.

Jove Kuang
  • 322
  • 2
  • 12
  • from the documentation at the link above: " the send() method returns immediately after dispatching the exchange to a thread pool for execution" - so, not really asynchronous. – kellogs Dec 11 '13 at 23:09