I have a REST endpoint and I want to access it using UDP for example Java Datagram. I know its not a best practice to try even but my recent project I have some hardware limitations. Hardware can make UDP calls only and my existing services are over REST i.e. HTTP/HTTPS.
I am looking for any way I can reuse my existing services. I have tried following code but received UnknownHostException
.
public class UDPClinet {
public static void main(String[] args) {
String hostname = "https://jsonplaceholder.typicode.com/posts/1";
int port = 80;
try {
InetAddress address = InetAddress.getByName(hostname);
DatagramSocket socket = new DatagramSocket();
while (true) {
DatagramPacket request = new DatagramPacket(new byte[1], 1, address, port);
socket.send(request);
byte[] buffer = new byte[512];
DatagramPacket response = new DatagramPacket(buffer, buffer.length);
socket.receive(response);
String quote = new String(buffer, 0, response.getLength());
System.out.println(quote);
System.out.println();
Thread.sleep(10000);
}
} catch (SocketTimeoutException ex) {
System.out.println("Timeout error: " + ex.getMessage());
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Client error: " + ex.getMessage());
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
Is it possible to implement a RESTful service that can be called via UDP.
Yes. (See below)
Can you call your existing RESTful service via UDP?
Probably no. And certainly not without a lot of work.
Typical RESTful services are in fact implemented using HTTP or HTTPS over TCP/IP connections. It is not possible to talk directly to an TCP-based service using UDP. The IP-level packets will have the wrong protocol family and the service's OS won't route them to the service.
However, it is possible (technically speaking) to implement RESTful services over any transport that is capable of sending messages. REST principles are agnostic of the transport protocol.
The problem will be finding a service framework that support RESTful UDP and (conventional) RESTful HTTP at the same time.
There are a couple of other practical problems:
UDP is unreliable, and this is exacerbated if you send datagrams that won't fit into a packet with the default MTU (1500 bytes). So if you want to implement a RESTful service over UDP, you will need to play close attention to the size of request and response payloads.
HTTPS uses TLS so that the client is able to validate the server's authenticity and then send data encrypted. TLS over UDP is possible (it is called DTLS) and supported by JCSE, but using it in a typical RESTful / HTTP framework may be challenging.
If you want to pursue this, look for a RESTful framework that implements CoAP (Constrained Application Protocol - RFC 7252) and DTLS.