java.net - JRE Emulation | JRE Emulation
package

java.net

Provides the classes for implementing networking applications.

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

Addresses are used throughout the java.net APIs as either host identifiers, or socket endpoint identifiers.

The InetAddress class is the abstraction representing an IP (Internet Protocol) address. It has two subclasses:

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.

About IPv6

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 getByName(String) are 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 Exception.

Sockets

Sockets are means to establish a communication link between machines over the network. The java.net package provides 4 kinds of Sockets:

  • Socket is a TCP client API, and will typically be used to {@linkplain java.net.Socket#connect(SocketAddress) connect} to a remote host.
  • ServerSocket is a TCP server API, and will typically {@linkplain java.net.ServerSocket#accept accept} connections from client sockets.
  • DatagramSocket is a UDP endpoint API and is used to {@linkplain java.net.DatagramSocket#send send} and {@linkplain java.net.DatagramSocket#receive receive} {@linkplain java.net.DatagramPacket datagram packets}.
  • MulticastSocket is a subclass of DatagramSocket used when dealing with multicast groups.

Sending and receiving with TCP sockets is done through InputStreams and OutputStreams which can be obtained via the getInputStream() and getOutputStream() methods.

Interfaces

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:

  • URI is 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.
  • URL is the class representing a Universal Resource Locator, which is both an older concept for URIs and a means to access the resources.
  • URLConnection is 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.
  • HttpURLConnection is a subclass of URLConnection and provides some additional functionalities specific to the HTTP protocol.

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 InputStream.

Here is an example:

 URI uri = new URI("http://java.sun.com/");
 URL url = uri.toURL();
 InputStream in = url.openStream();
 

Protocol Handlers

As 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 add to the search path by setting the java.protocol.handler.pkgs system property. For instance if it is set to myapp.protocols, then the URL code will try, in the case of http, first to load myapp.protocols.http.Handler, then, if this fails, http.Handler from the default location.

Note that the Handler class has to be a subclass of the abstract class URLStreamHandler.

Additional Specification

Interfaces

ContentHandlerFactory Defines a factory which is responsible for creating a ContentHandler
CookiePolicy CookiePolicy has three pre-defined policy. 
CookieStore A CookieStore object is a repository for cookies. 
DatagramSocketImplFactory This interface defines a factory for datagram socket implementations. 
FileNameMap Defines a scheme for mapping a filename type to a MIME content type. 
SocketImplFactory This interface defines a factory for socket implementations. 
SocketOptions Defines an interface for socket implementations to get and set socket options. 
URLStreamHandlerFactory Defines a factory which creates an URLStreamHandler for a specified protocol. 

Classes

Authenticator An implementation of this class is able to obtain authentication information for a connection in several ways. 
CacheRequest CacheRequest is a kind of channel for storing resource data in the ResponseCache
CacheResponse A response cache entry. 
ContentHandler This class converts the content of a certain format (i.e. 
CookieHandler This class provides a way to manage cookies with a HTTP protocol handler. 
CookieManager This class provides a concrete implementation of CookieHandler. 
DatagramPacket This class represents a datagram packet which contains data either to be sent or received through a DatagramSocket
DatagramSocket This class implements a UDP socket for sending and receiving DatagramPacket
DatagramSocketImpl The abstract superclass for datagram and multicast socket implementations. 
HttpCookie An opaque key-value value pair held by an HTTP client to permit a stateful session with an HTTP server. 
HttpURLConnection An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. 
IDN Converts internationalized domain names between Unicode and the ASCII Compatible Encoding (ACE) representation. 
Inet4Address An IPv4 address. 
Inet6Address An IPv6 address. 
InetAddress An Internet Protocol (IP) address. 
InetSocketAddress This class represents a socket endpoint described by a IP address and a port number. 
InterfaceAddress Identifies one of a network interface's addresses. 
MulticastSocket This class implements a multicast socket for sending and receiving IP multicast datagram packets. 
NetFactory  
NetFactoryImpl  
NetPermission Legacy security code; do not use. 
NetworkInterface This class is used to represent a network interface of the local device. 
PasswordAuthentication This immutable class is a data structure that encapsulates username and password which is used by the Authenticator class. 
Proxy This class represents proxy server settings. 
ProxySelector Selects the proxy server to use, if any, when connecting to a given URL. 
ResponseCache Caches URLConnection responses. 
SecureCacheResponse A secure cache response represents data which is originally retrieved over a secure connection. 
ServerSocket This class represents a server-side socket that waits for incoming client connections. 
Socket Provides a client-side TCP socket. 
SocketAddress This abstract class represents a protocol-independent base for socket-endpoint representing classes. 
SocketImpl This class is the base of all streaming socket implementation classes. 
SocketPermission Legacy security code; do not use. 
URI A Uniform Resource Identifier that identifies an abstract or physical resource, as specified by RFC 2396
URL A Uniform Resource Locator that identifies the location of an Internet resource as specified by RFC 1738
URLClassLoader This class loader is responsible for loading classes and resources from a list of URLs which can refer to either directories or JAR files. 
URLConnection A connection to a URL for reading or writing. 
URLDecoder This class is used to decode a string which is encoded in the application/x-www-form-urlencoded MIME content type. 
URLEncoder This class is used to encode a string using the format required by application/x-www-form-urlencoded MIME content type. 
URLStreamHandler The abstract class URLStreamHandler is the base for all classes which can handle the communication with a URL object over a particular protocol type. 

Enums

Authenticator.RequestorType Enumeration class for the origin of the authentication request. 
Proxy.Type Enum class for the proxy type. 

Exceptions

BindException Signals that an error occurred while attempting to bind a socket to a local address and port. 
ConnectException Signals that an error occurred while attempting to connect a socket to a remote address and port. 
HttpRetryException Thrown to indicate that a HTTP request needs to be retried but cannot be retried automatically, due to streaming mode being enabled. 
MalformedURLException Thrown to indicate that a malformed URL has occurred. 
NoRouteToHostException Signals that an error occurred while attempting to connect a socket to a remote address and port. 
PortUnreachableException Signals that an ICMP Port Unreachable message has been received on a connected datagram. 
ProtocolException Thrown to indicate that there is an error in the underlying protocol, such as a TCP error. 
SocketException Thrown to indicate that there is an error creating or accessing a Socket. 
SocketTimeoutException Signals that a timeout has occurred on a socket read or accept. 
UnknownHostException Thrown to indicate that the IP address of a host could not be determined. 
UnknownServiceException Thrown to indicate that an unknown service exception has occurred. 
URISyntaxException Checked exception thrown to indicate that a string could not be parsed as a URI reference.