The java.net package can be roughly divided in two sections:
A Low Level API, which deals with the following abstractions:
Addresses, which are networking identifiers, like IP addresses.
Sockets, which are basic bidirectional data communication mechanisms.
Interfaces, which describe network interfaces.
A High Level API, which deals with the following abstractions:
URIs, which represent Universal Resource Identifiers.
URLs, which represent Universal Resource Locators.
Connections, which represents connections to the resource pointed to by URLs.
Addresses are used throughout the java.net APIs as either host identifiers, or socket endpoint identifiers.
InetAddress class is the abstraction representing an
IP (Internet Protocol) address. It has two subclasses:
Inet4Addressfor IPv4 addresses.
Inet6Addressfor IPv6 addresses.
But, in most cases, there is no need to deal directly with the subclasses, as the InetAddress abstraction should cover most of the needed functionality.
Not all systems have support for the IPv6 protocol, and while the Java
networking stack will attempt to detect it and use it transparently when
available, it is also possible to disable its use with a system property.
In the case where IPv6 is not available, or explicitly disabled,
Inet6Address are not valid arguments for most networking operations any
more. While methods like
guaranteed not to return an Inet6Address when looking up host names, it
is possible, by passing literals, to create such an object. In which
case, most methods, when called with an Inet6Address will throw an
Sockets are means to establish a communication link between machines over the network. The java.net package provides 4 kinds of Sockets:
Socketis a TCP client API, and will typically be used to connect to a remote host.
ServerSocketis a TCP server API, and will typically accept connections from client sockets.
DatagramSocketis a UDP endpoint API and is used to send and receive datagram packets.
MulticastSocketis a subclass of
DatagramSocketused when dealing with multicast groups.
Sending and receiving with TCP sockets is done through InputStreams and
OutputStreams which can be obtained via the
NetworkInterface class provides APIs to browse and
query all the networking interfaces (e.g. ethernet connection or PPP
endpoint) of the local machine. It is through that class that you can
check if any of the local interfaces is configured to support IPv6.
Note, all conforming implementations must support at least one
NetworkInterface object, which must either be connected to a
network, or be a "loopback" interface that can only communicate with
entities on the same machine.
High level API
A number of classes in the java.net package do provide for a much higher level of abstraction and allow for easy access to resources on the network. The classes are:
URIis the class representing a Universal Resource Identifier, as specified in RFC 2396. As the name indicates, this is just an Identifier and doesn't provide directly the means to access the resource.
URLis the class representing a Universal Resource Locator, which is both an older concept for URIs and a means to access the resources.
URLConnectionis created from a URL and is the communication link used to access the resource pointed by the URL. This abstract class will delegate most of the work to the underlying protocol handlers like http or https.
HttpURLConnectionis a subclass of URLConnection and provides some additional functionalities specific to the HTTP protocol. This API has been superseded by the newer HTTP Client API.
The recommended usage is to use
URI to identify
resources, then convert it into a
URL when it is time to
access the resource. From that URL, you can either get the
URLConnection for fine control, or get directly the
Here is an example:
URI uri = new URI("http://www.example.com/"); URL url = uri.toURL(); InputStream in = url.openStream();
Protocol HandlersAs mentioned, URL and URLConnection rely on protocol handlers which must be present, otherwise an Exception is thrown. This is the major difference with URIs which only identify resources, and therefore don't need to have access to the protocol handler. So, while it is possible to create an URI with any kind of protocol scheme (e.g.
myproto://myhost.mydomain/resource/), a similar URL will try to instantiate the handler for the specified protocol; if it doesn't exist an exception will be thrown.
By default the protocol handlers are loaded dynamically from the default
location. It is, however, possible to deploy additional protocols handlers
services. Service providers of type
URLStreamHandlerProvider are located at
runtime, as specified in the URL constructor.
Interface Summary Interface Description ContentHandlerFactoryThis interface defines a factory for content handlers. CookiePolicyCookiePolicy implementations decide which cookies should be accepted and which should be rejected. CookieStoreA CookieStore object represents a storage for cookie. DatagramSocketImplFactoryThis interface defines a factory for datagram socket implementations. FileNameMapA simple interface which provides a mechanism to map between a file name and a MIME type string. ProtocolFamilyRepresents a family of communication protocols. SocketImplFactoryThis interface defines a factory for socket implementations. SocketOption<T>A socket option associated with a socket. SocketOptionsInterface of methods to get/set socket options. URLStreamHandlerFactoryThis interface defines a factory for
URLstream protocol handlers.
Class Summary Class Description AuthenticatorThe class Authenticator represents an object that knows how to obtain authentication for a network connection. CacheRequestRepresents channels for storing resources in the ResponseCache. CacheResponseRepresent channels for retrieving resources from the ResponseCache. ContentHandlerThe abstract class
ContentHandleris the superclass of all classes that read an
CookieHandlerA CookieHandler object provides a callback mechanism to hook up a HTTP state management policy implementation into the HTTP protocol handler. CookieManagerCookieManager provides a concrete implementation of
CookieHandler, which separates the storage of cookies from the policy surrounding accepting and rejecting cookies.
DatagramPacketThis class represents a datagram packet. DatagramSocketThis class represents a socket for sending and receiving datagram packets. DatagramSocketImplAbstract datagram and multicast socket implementation base class. HttpCookieAn HttpCookie object represents an HTTP cookie, which carries state information between server and user agent. HttpURLConnectionA URLConnection with support for HTTP-specific features. IDNProvides methods to convert internationalized domain names (IDNs) between a normal Unicode representation and an ASCII Compatible Encoding (ACE) representation. Inet4AddressThis class represents an Internet Protocol version 4 (IPv4) address. Inet6AddressThis class represents an Internet Protocol version 6 (IPv6) address. InetAddressThis class represents an Internet Protocol (IP) address. InetSocketAddressThis class implements an IP Socket Address (IP address + port number) It can also be a pair (hostname + port number), in which case an attempt will be made to resolve the hostname. InterfaceAddressThis class represents a Network Interface address. JarURLConnectionA URL Connection to a Java ARchive (JAR) file or an entry in a JAR file. MulticastSocketThe multicast datagram socket class is useful for sending and receiving IP multicast packets. NetPermissionThis class is for various network permissions. NetworkInterfaceThis class represents a Network Interface made up of a name, and a list of IP addresses assigned to this interface. PasswordAuthenticationThe class PasswordAuthentication is a data holder that is used by Authenticator. ProxyThis class represents a proxy setting, typically a type (http, socks) and a socket address. ProxySelectorSelects the proxy server to use, if any, when connecting to the network resource referenced by a URL. ResponseCacheRepresents implementations of URLConnection caches. SecureCacheResponseRepresents a cache response originally retrieved through secure means, such as TLS. ServerSocketThis class implements server sockets. SocketThis class implements client sockets (also called just "sockets"). SocketAddressThis class represents a Socket Address with no protocol attachment. SocketImplThe abstract class
SocketImplis a common superclass of all classes that actually implement sockets.
SocketPermissionThis class represents access to a network via sockets. StandardSocketOptionsDefines the standard socket options. URIRepresents a Uniform Resource Identifier (URI) reference. URLClass
URLrepresents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web.
URLClassLoaderThis class loader is used to load classes and resources from a search path of URLs referring to both JAR files and directories. URLConnectionThe abstract class
URLConnectionis the superclass of all classes that represent a communications link between the application and a URL.
URLDecoderUtility class for HTML form decoding. URLEncoderUtility class for HTML form encoding. URLPermissionRepresents permission to access a resource or set of resources defined by a given url, and for a given set of user-settable request methods and request headers. URLStreamHandlerThe abstract class
URLStreamHandleris the common superclass for all stream protocol handlers.
Enum Summary Enum Description Authenticator.RequestorTypeThe type of the entity requesting authentication. Proxy.TypeRepresents the proxy type. StandardProtocolFamilyDefines the standard families of communication protocols.
Exception Summary Exception Description BindExceptionSignals that an error occurred while attempting to bind a socket to a local address and port. ConnectExceptionSignals that an error occurred while attempting to connect a socket to a remote address and port. HttpRetryExceptionThrown to indicate that a HTTP request needs to be retried but cannot be retried automatically, due to streaming mode being enabled. MalformedURLExceptionThrown to indicate that a malformed URL has occurred. NoRouteToHostExceptionSignals that an error occurred while attempting to connect a socket to a remote address and port. PortUnreachableExceptionSignals that an ICMP Port Unreachable message has been received on a connected datagram. ProtocolExceptionThrown to indicate that there is an error in the underlying protocol, such as a TCP error. SocketExceptionThrown to indicate that there is an error creating or accessing a Socket. SocketTimeoutExceptionSignals that a timeout has occurred on a socket read or accept. UnknownHostExceptionThrown to indicate that the IP address of a host could not be determined. UnknownServiceExceptionThrown to indicate that an unknown service exception has occurred. URISyntaxExceptionChecked exception thrown to indicate that a string could not be parsed as a URI reference.