Sid Prasad
Sid Prasad

Reputation: 157

HTTP requests without waiting for response

Is it possible to send an HTTP request without waiting for a response?

I'm working on an IoT project that requires logging of data from sensors. In every setup, there are many sensors, and one central coordinator (Will mostly be implemented with Raspberry Pi) which gathers data from the sensors and sends the data to the server via the internet.

This logging happens every second. Therefore, the sending of data should happen quickly so that the queue does not become too large. If the request doesn't wait for a response (like UDP), it would be much faster.

It is okay if few packets are dropped every now and then.

Also, please do tell me the best way to implement this. Preferably in Java.

The server side is implemented using PHP.

Thanks in advance!

EDIT: The sensors are wireless, but the tech they use has very little (or no) latency in sending to the coordinator. This coordinator has to send the data over the internet. But, just assume the internet connection is bad. As this is going to be implemented in a remote part of India.

Upvotes: 4

Views: 13976

Answers (2)

Chris Dennett
Chris Dennett

Reputation: 22721

You can set the TCP timeout for a GET request to less than a second, and keep retriggering the access in a thread. Use more threads for more devices.

Something like:

HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(1000); //set timeout to 1 second
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
   ...
}

Sleep the thread for the remainder of 1 second if the access is less than a second. You can consume the results on another thread if you add the results to thread-safe queues. Make sure to handle exceptions.

You can't use UDP with HTTP, HTTP is TCP only.

Upvotes: 2

Robert
Robert

Reputation: 42585

You are looking for an asynchronous HTTP library such as OkHttp. It allows to specify a Callback that is executed asynchronous (by a second thread). Therefore your main thread continues execution.

Upvotes: 2

Related Questions