You need to read from a URL, for example, to connect to a RESTful web service or to download a web page or other resource over HTTP/HTTPS.
Use the standard Java 11 HttpClient
or the URLConnection
class.
This technique applies anytime you need to read from a URL, not just a RESTful web service.
You need to contact a server using TCP/IP.
Just create a java.net.Socket
, passing the hostname and port number into the constructor.
You want to look up a host’s address name or number or get the address at the other end of a network connection.
Get an InetAddress
object.
Having connected, you wish to transfer textual data.
Construct a BufferedReader
or PrintWriter
from the socket’s getInputStream()
or getOutputStream()
.
Example:
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
Having connected, you wish to transfer binary data, either raw binary data or serialized Java objects.
For plain binary data, construct a DataInputStream
or DataOutputStream
from the socket’s getInputStream()
or getOutputStream()
. For serialized Java object data, construct an ObjectInputStream
or ObjectOutputStream
.
If the volume of data might be large, insert a buffered stream for efficiency:
DataInputStream is = new DataInputStream(new BufferedInputStream(sock.getInputStream()));
DataOutputStream is = new DataOutputStream(new BufferedOutputStream(sock.getOutputStream()));
You need to use a datagram connection (UDP) instead of a stream connection (TCP).
Use DatagramSocket
and DatagramPacket
.