Networking in Java
Programming in Java can run on several devices connected by a network thanks to networking. By providing the classes and interfaces required for low-level communication, the java.net
package frees developers from having to worry about complex communication intricacies and lets them concentrate on solving problems. Java is compatible with the popular User Datagram Protocol (UDP) and Transmission Control Protocol (TCP) protocols.
URL Class: Representing Uniform Resource Locators
An FTP directory or webpage on the World Wide Web is identified by its Uniform Resource Locator (URL). URLs are essential for addressing material on the Internet in a unique way.
There are multiple components to a URL:
- Protocol: Defines the communication method (e.g., HTTP, HTTPS, FTP, File).
- Host: The domain name or IP address of the server (also called authority).
- Port: An optional parameter specifying the port number. If not specified, the protocol’s default port is used (e.g., port 80 for HTTP).
- Path/File: The actual file path to the resource.
- Query: Optional parameters passed to the resource, often preceded by a question mark
?
. - Reference (Ref): An internal anchor within the resource, preceded by a hash
#
.
The URL
class in Java provides constructors for creating URL objects and methods for manipulating them.
Some useful URL
constructors include:
URL(String url)
: Creates a URL from a given string (e.g.,"http://www.example.com/index.htm"
).URL(String protocol, String host, int port, String file)
: Constructs a URL from its individual components.
You can retrieve the components of the URL class using its key methods:
getProtocol()
: Returns the protocol.getHost()
: Returns the host name.getPort()
: Returns the port number, or -1 if not explicitly set.getDefaultPort()
: Returns the default port for the protocol.getFile()
: Returns the filename/path.getQuery()
: Returns the query part.getRef()
: Returns the reference part.toExternalForm()
: Returns the URL as a string.
Here’s an example demonstrating the URL
class:
// File Name : URLDemo.java
import java.net.*;
import java.io.*;
public class URLDemo {
public static void main(String[] args) {
try {
URL url = new URL("http://www.amrood.com/index.htm?language=en#j2se");
System.out.println("URL is " + url.toString());
System.out.println("protocol is " + url.getProtocol());
System.out.println("authority is " + url.getAuthority());
System.out.println("file name is " + url.getFile());
System.out.println("host is " + url.getHost());
System.out.println("path is " + url.getPath());
System.out.println("port is " + url.getPort());
System.out.println("default port is " + url.getDefaultPort());
System.out.println("query is " + url.getQuery());
System.out.println("ref is " + url.getRef());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
URL is http://www.amrood.com/index.htm?language=en#j2se
protocol is http
authority is www.amrood.com
file name is /index.htm?language=en
host is www.amrood.com
path is /index.htm
port is -1
default port is 80
query is language=en
ref is j2se
URLConnection and HttpURLConnection
An abstract class called the URLConnection
class offers a versatile way to retrieve a remote resource’s properties. The openConnection()
method is called on a URL
object to obtain a URLConnection
object. Before moving its contents, you can check the resource’s attributes thanks to this.
Key URLConnection
techniques include:
getContent()
: Retrieves the contents of the URL connection.getContentLength()
: Returns the size of the content in bytes.getContentType()
: Returns the content-type header field value.getInputStream()
: Returns an InputStream linked to the resource, used for reading the content.getOutputStream()
: Returns anOutputStream
for writing to the resource (if supported).setDoInput(boolean input)
: Sets whether the connection will be used for input (defaulttrue
).setDoOutput(boolean output)
: Sets whether the connection will be used for output (defaultfalse
).
Specifically made for HTTP connections, the HttpURLConnection
class is a subclass of URLConnection
. The URLConnection
object that openConnection()
returns is cast to a HttpURLConnection
in the event that the protocol is HTTP. Access to HTTP-specific functionalities is thus made possible.
Key HttpURLConnection techniques consist of:
getRequestMethod()
: Returns the HTTP request method (e.g., GET, POST).getResponseCode()
: Returns the HTTP response code (e.g., 200 for OK, 404 for Not Found).getResponseMessage()
: Returns the response message associated with the response code.setFollowRedirects(boolean how)
: Controls whether redirects are automatically followed.setRequestMethod(String how)
: Sets the HTTP request method.
Here’s an example using HttpURLConnection
to interact with a web resource:
// Demonstrate HttpURLConnection.
import java.net.*;
import java.io.*;
import java.util.*;
class HttpURLDemo {
public static void main(String args[]) throws Exception {
URL hp = new URL("http://www.google.com");
HttpURLConnection hpCon = (HttpURLConnection) hp.openConnection();
// Display request method.
System.out.println("Request method is " + hpCon.getRequestMethod());
// Display response code.
System.out.println("Response code is " + hpCon.getResponseCode());
// Display response message.
System.out.println("Response Message is " + hpCon.getResponseMessage());
// Get a list of the header fields and a set of the header keys.
Map<String, List<String>> hdrMap = hpCon.getHeaderFields();
Set<String> hdrField = hdrMap.keySet();
System.out.println("\nHere is the header:");
// Display all header keys and values.
for (String k : hdrField) {
System.out.println("Key: " + k + " Value: " + hdrMap.get(k));
}
}
}
Output (Note: actual output may vary depending on Google’s headers):
Request method is GET
Response code is 200
Response Message is OK
Here is the header:
Key: null Value: [HTTP/1.1 200 OK]
Key: Content-Type Value: [text/html; charset=ISO-8859-1]
Key: Date Value: [Wed, 15 May 2024 10:00:00 GMT]
Key: Server Value: [gws]
Key: X-XSS-Protection Value:
Key: X-Frame-Options Value: [SAMEORIGIN]
Key: Expires Value: [Wed, 15 May 2024 10:00:00 GMT]
Key: Cache-Control Value: [private, max-age=0]
Key: Set-Cookie Value: [A=B; C=D; path=/; domain=.google.com]
Key: P3P Value: [CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."]
Key: Vary Value: [Accept-Encoding]
Basic Socket Programming
A low-level network interface is offered via sockets, which act as an endpoint for a two-way communication channel between two programs, sometimes running on separate computers. This idea is essential to network programming. While server applications utilise java.net.ServerSocket
to listen for client requests on a port, java.net.Socket
in Java represents a client socket.
A TCP connection entails the following actions:
- Server side: Creates a
ServerSocket
object, then calls itsaccept()
function to wait for a client to connect after providing a port number. - Client side: Creates a
socket
object by passing it the port number and server name. Implicitly, this constructor tries to establish a connection with the server. - Following a successful connection, the client and server now have
Socket
objects for communication when the server’saccept()
method produces a newSocket
object.
Then, via I/O streams, communication takes place: the client’s OutputStream
is linked to the server’s InputStream
, and vice versa.
There are multiple constructors available for client sockets in the Socket
class. A popular one that connects to the given host and port is Socket(String hostName, int port)
.
Important client socket techniques consist of:
getInputStream()
: Returns theInputStream
associated with the socket to read incoming data.getOutputStream()
: Returns theOutputStream
associated with the socket to send outgoing data.close()
: Closes the socket, which also closes its associated I/O streams.
Here is a simplified client-side socket example using the Whois
client example from the sources:
// Demonstrate Sockets (Whois Client).
import java.net.*;
import java.io.*;
class Whois {
public static void main(String args[]) throws Exception {
int c;
// Create a socket connected to internic.net, port 43 (whois service).
Socket s = new Socket("whois.internic.net", 43);
// Obtain input and output streams.
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
// Construct a request string.
String str = (args.length == 0 ? "MHProfessional.com" : args) + "\n";
// Convert to bytes.
byte buf[] = str.getBytes();
// Send request.
out.write(buf);
// Read and display response.
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
s.close(); // Close the socket.
}
}
To run this example:
- Compile:
javac Whois.java
- Execute:
java Whois
(orjava Whois example.com
)
Output (for java Whois):
[Whois server response for MHProfessional.com, including domain registration details, name servers, etc.]
This client application connects to a “whois” server, requests a domain name, and then prints the data that the server has returned. An application can listen for incoming client connections when using the ServerSocket
class for server-side functions. After a connection is approved, a new Socket
object is made for that particular client’s communication.
Java useful for networking
It’s true that Java is great for internet-based networking. When it comes to building Internet-based software and applications that communicate via a network, it is regarded as the “preeminent language of the Internet” and the preferred language.
Classes and interfaces for low-level communication are provided by the java.net
package in Java’s standard API, which offers comprehensive support for network development. Java manages TCP/IP protocols, including UDP (User Datagram Protocol) for connectionless data packet transmission as well as TCP (Transmission Control Protocol) for dependable, stream-based communication.
This makes it possible for:
- Socket Programming: Socket programming is the process of using the
Socket
(client) andServerSocket
(server) classes to create two-way communication links between programs, frequently running on different computers. - URL Processing: Using classes such as
URL
,URLConnection
, andHttpURLConnection
to open connections and read data from web resources, as well as working with Uniform Resource Locators (URLs) to represent resources on the World Wide Web.
Additionally, servlets, which dynamically expand the capability of web servers across both client and server sides of the connection, were developed as a result of Java’s networking utility.