V. Java Networking

 

5. Java Networking

Java networking (or, Java network programming) refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

Advantages of Java Networking

  • Creating server-client applications
  • Implementing networking protocols
  • Implement socket programming
  • Creating web services

Package Used in Networking

The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand.

The java.net package provides support for the two common network protocols −

  • TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.
  • UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications.

This chapter gives a good understanding on the following two subjects −

  • Socket Programming − This is the most widely used concept in Networking and it has been explained in very detail.
  • URL Processing − This would be covered separately. Click here to learn about URL Processing in Java language.

Socket Programming in Java Networking

Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

When the connection is made, the server creates a socket object on its end of the communication. The client and the server can now communicate by writing to and reading from the socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them.

The following steps occur when establishing a TCP connection between two computers using sockets −

  • The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
  • The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.
  • After the server is waiting, a client instantiates a Socket object, specifying the server name and the port number to connect to.
  • The constructor of the Socket class attempts to connect the client to the specified server and the port number. If communication is established, the client now has a Socket object capable of communicating with the server.
  • On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.

After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream.

TCP is a two-way communication protocol, hence data can be sent across both streams at the same time. Following are the useful classes providing complete set of methods to implement sockets.

ServerSocket Class Constructors

The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests.

The ServerSocket class has four constructors −

Sr.No.

Method & Description

1

public ServerSocket(int port) throws IOException

Attempts to create a server socket bound to the specified port. An exception occurs if the port is already bound by another application.

2

public ServerSocket(int port, int backlog) throws IOException

Similar to the previous constructor, the backlog parameter specifies how many incoming clients to store in a wait queue.

3

public ServerSocket(int port, int backlog, InetAddress address) throws IOException

Similar to the previous constructor, the InetAddress parameter specifies the local IP address to bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the server to specify which of its IP addresses to accept client requests on.

4

public ServerSocket() throws IOException

Creates an unbound server socket. When using this constructor, use the bind() method when you are ready to bind the server socket.

If the ServerSocket constructor does not throw an exception, it means that your application has successfully bound to the specified port and is ready for client requests.

ServerSocket Class Methods

Following are some of the common methods of the ServerSocket class −

Sr.No.

Method & Description

1

public int getLocalPort()

Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port number in a constructor and let the server find a port for you.

2

public Socket accept() throws IOException

Waits for an incoming client. This method blocks until either a client connects to the server on the specified port or the socket times out, assuming that the time-out value has been set using the setSoTimeout() method. Otherwise, this method blocks indefinitely.

3

public void setSoTimeout(int timeout)

Sets the time-out value for how long the server socket waits for a client during the accept().

4

public void bind(SocketAddress host, int backlog)

Binds the socket to the specified server and port in the SocketAddress object. Use this method if you have instantiated the ServerSocket using the no-argument constructor.

When the ServerSocket invokes accept(), the method does not return until a client connects. After a client does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this new Socket. A TCP connection now exists between the client and the server, and communication can begin.

Socket Class Constructors

The java.net.Socket class represents the socket that both the client and the server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method.

The Socket class has five constructors that a client uses to connect to a server −

Sr.No.

Method & Description

1

public Socket(String host, int port) throws UnknownHostException, IOException.

This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server.

2

public Socket(InetAddress host, int port) throws IOException

This method is identical to the previous constructor, except that the host is denoted by an InetAddress object.

3

public Socket(String host, int port, InetAddresslocalAddress, int localPort) throws IOException.

Connects to the specified host and port, creating a socket on the local host at the specified address and port.

4

public Socket(InetAddress host, int port, InetAddresslocalAddress, int localPort) throws IOException.

This method is identical to the previous constructor, except that the host is denoted by an InetAddress object instead of a String.

5

public Socket()

Creates an unconnected socket. Use the connect() method to connect this socket to a server.

When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port.

Socket Class Methods

Some methods of interest in the Socket class are listed here. Notice that both the client and the server have a Socket object, so these methods can be invoked by both the client and the server.

Sr.No.

Method & Description

1

public void connect(SocketAddress host, int timeout) throws IOException

This method connects the socket to the specified host. This method is needed only when you instantiate the Socket using the no-argument constructor.

2

public InetAddressgetInetAddress()

This method returns the address of the other computer that this socket is connected to.

3

public int getPort()

Returns the port the socket is bound to on the remote machine.

4

public int getLocalPort()

Returns the port the socket is bound to on the local machine.

5

public SocketAddressgetRemoteSocketAddress()

Returns the address of the remote socket.

6

public InputStreamgetInputStream() throws IOException

Returns the input stream of the socket. The input stream is connected to the output stream of the remote socket.

7

public OutputStreamgetOutputStream() throws IOException

Returns the output stream of the socket. The output stream is connected to the input stream of the remote socket.

8

public void close() throws IOException

Closes the socket, which makes this Socket object no longer capable of connecting again to any server.

InetAddress Class Methods

This class represents an Internet Protocol (IP) address. Here are following usefull methods which you would need while doing socket programming −

Sr.No.

Method & Description

1

static InetAddressgetByAddress(byte[] addr)

Returns an InetAddress object given the raw IP address.

2

static InetAddressgetByAddress(String host, byte[] addr)

Creates an InetAddress based on the provided host name and IP address.

3

static InetAddressgetByName(String host)

Determines the IP address of a host, given the host's name.

4

String getHostAddress()

Returns the IP address string in textual presentation.

5

String getHostName()

Gets the host name for this IP address.

6

static InetAddressInetAddressgetLocalHost()

Returns the local host.

7

String toString()

Converts this IP address to a String.

Example of Java Networking

Implementing Socket Client in Java

The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response.

Example: Socket Client

// File Name GreetingClient.java

import java.net.*;

import java.io.*;

 

public class GreetingClient {

 

   public static void main(String [] args) {

      String serverName = args[0];

      int port = Integer.parseInt(args[1]);

      try {

System.out.println("Connecting to " + serverName + " on port " + port);

         Socket client = new Socket(serverName, port);

 

System.out.println("Just connected to " + client.getRemoteSocketAddress());

OutputStreamoutToServer = client.getOutputStream();

DataOutputStream out = new DataOutputStream(outToServer);

 

out.writeUTF("Hello from " + client.getLocalSocketAddress());

InputStreaminFromServer = client.getInputStream();

DataInputStream in = new DataInputStream(inFromServer);

 

System.out.println("Server says " + in.readUTF());

client.close();

      } catch (IOException e) {

e.printStackTrace();

      }

   }

}

Implementing Socket Server in Java

The following GreetingServer program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument −

Example: Socket Server

// File Name GreetingServer.java

import java.net.*;

import java.io.*;

 

public class GreetingServer extends Thread {

   private ServerSocketserverSocket;

 

   public GreetingServer(int port) throws IOException {

serverSocket = new ServerSocket(port);

serverSocket.setSoTimeout(10000);

   }

 

   public void run() {

      while(true) {

         try {

System.out.println("Waiting for client on port " +

serverSocket.getLocalPort() + "...");

            Socket server = serverSocket.accept();

 

System.out.println("Just connected to " + server.getRemoteSocketAddress());

DataInputStream in = new DataInputStream(server.getInputStream());

 

System.out.println(in.readUTF());

DataOutputStream out = new DataOutputStream(server.getOutputStream());

out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()

               + "\nGoodbye!");

server.close();

 

         } catch (SocketTimeoutException s) {

System.out.println("Socket timed out!");

            break;

         } catch (IOException e) {

e.printStackTrace();

            break;

         }

      }

   }

 

   public static void main(String [] args) {

      int port = Integer.parseInt(args[0]);

      try {

         Thread t = new GreetingServer(port);

t.start();

      } catch (IOException e) {

e.printStackTrace();

      }

   }

}

Compile the client and the server and then start the server as follows −

$ java GreetingServer 6066

Waiting for client on port 6066...

Check the client program as follows −

 

Output


$ java GreetingClient localhost 6066

Connecting to localhost on port 6066

Just connected to localhost/127.0.0.1:6066

Server says Thank you for connecting to /127.0.0.1:6066

Goodbye!

Socket Programming in Java

Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

When the connection is made, the server creates a socket object on its end of the communication. The client and the server can now communicate by writing to and reading from the socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them.

Steps of Socket Programming in Java

The following steps occur when establishing a TCP connection between two computers using sockets −

  • The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
  • The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.
  • After the server is waiting, a client instantiates a Socket object, specifying the server name and the port number to connect to.
  • The constructor of the Socket class attempts to connect the client to the specified server and the port number. If communication is established, the client now has a Socket object capable of communicating with the server.
  • On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.

After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream. TCP is a two-way communication protocol, hence data can be sent across both streams at the same time.

Advantages of Java Socket Programming

  • Platform Independence − One of the biggest advantages of Java Sockets is that they are platform-independent. This means that the same Java code can be run on multiple operating systems and devices without the need for modification. This allows for easy deployment of network-based applications across different systems and ensures that the application can be run on different devices without the need for platform-specific code.
  • Easy to Use − Java Sockets are also relatively easy to use, even for developers who are new to network programming. The Java API provides a simple, consistent interface for creating and managing sockets, which makes it easy to implement network-based applications without needing to understand the underlying network protocols.
  • Scalability − Java Sockets are highly scalable, making them suitable for large-scale network-based applications. They can easily handle thousands of simultaneous connections and can be used to create distributed systems that can handle high levels of traffic.
  • Security − Java Sockets provide built-in support for secure communication, including SSL and TLS encryption. This makes it easy to create secure network-based applications and ensures that sensitive data is protected while in transit.
  • Multithreading − Java Sockets support multithreading, which means that multiple threads can be used to handle multiple connections simultaneously. This improves the performance of network-based applications and allows them to handle a large number of requests without becoming overloaded.

Disadvantages of Java Socket Programming

  • Complexity − While Java Sockets are relatively easy to use, they can still be complex to implement, particularly for developers who are new to network programming. This complexity can make it difficult to debug and troubleshoot network-based applications, which can be time-consuming and frustrating.
  • Latency − Java Sockets can introduce latency into network-based applications, particularly when dealing with large amounts of data. This can be a problem for applications that require real-time communication, such as online gaming or video conferencing.
  • Resource Intensive − Java Sockets can be resource-intensive, particularly when dealing with large numbers of connections or large amounts of data. This can be a problem for systems with limited resources, such as mobile devices or embedded systems.
  • Limited Protocol Support − Java Sockets support a limited number of network protocols, which can be a limitation for certain types of network-based applications. This can make it difficult to create applications that need to communicate with other systems using proprietary protocols.
  • Potential for Security Vulnerabilities − Java Sockets, like any network-based application, are vulnerable to security threats, such as hacking and man-in-the-middle attacks. Careful attention must be paid to security when designing and implementing Java Socket-based systems to ensure that sensitive data is protected and potential vulnerabilities are identified and addressed.

Socket Programming Applications

  • Chat Applications − Java Sockets are often used to create chat applications, such as instant messaging programs and online chat rooms. These types of applications typically use a client-server architecture, where clients connect to a central server to send and receive messages.
  • File Transfer Applications − Java Sockets can also be used to create file transfer applications, such as peer-to-peer file sharing programs. These types of applications use a peer-to-peer architecture, where each device acts as both a client and a server. This allows for direct communication between devices, which can improve the speed and reliability of file transfers.
  • Remote Control Applications − Java Sockets can also be used to create remote control applications, such as remote desktop software. These types of applications use a client-server architecture, where a client connects to a remote server to control the desktop of the server. This allows users to access and control their desktop from any device with an internet connection.
  • Multiplayer Games − Java Sockets are also commonly used to create multiplayer games, such as online role-playing games and first-person shooters. These types of applications typically use a client-server architecture, where clients connect to a central server to play the game. The server acts as the intermediary between clients, handling communication and game logic.
  • IoT Applications − Java Sockets can also be used in IoT (Internet of Things) applications, such as smart home systems. These types of applications use a client-server architecture, where IoT devices connect to a central server to send and receive data. This allows for remote monitoring and control of the devices, as well as data collection and analysis.

Socket Programming Example

Example: Socket Client

The following GreetingClient is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response.

// File Name GreetingClient.java

import java.net.*;

import java.io.*;

 

public class GreetingClient {

 

   public static void main(String [] args) {

      String serverName = args[0];

      int port = Integer.parseInt(args[1]);

      try {

System.out.println("Connecting to " + serverName + " on port " + port);

         Socket client = new Socket(serverName, port);

 

System.out.println("Just connected to " + client.getRemoteSocketAddress());

OutputStreamoutToServer = client.getOutputStream();

DataOutputStream out = new DataOutputStream(outToServer);

 

out.writeUTF("Hello from " + client.getLocalSocketAddress());

InputStreaminFromServer = client.getInputStream();

DataInputStream in = new DataInputStream(inFromServer);

 

System.out.println("Server says " + in.readUTF());

client.close();

      } catch (IOException e) {

e.printStackTrace();

      }

   }

}

Compile the client and the server and then start the server as follows −

$ java GreetingServer 6066

Waiting for client on port 6066...

Check the client program as follows −

Output

$ java GreetingClient localhost 6066

Connecting to localhost on port 6066

Just connected to localhost/127.0.0.1:6066

Server says Thank you for connecting to /127.0.0.1:6066

Goodbye!

URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Web page or FTP directory.

This section shows you how to write Java programs that communicate with a URL. A URL can be broken down into parts, as follows −

protocol://host:port/path?query#ref

Examples of protocols include HTTPHTTPS, FTP, and File. The path is also referred to as the filename, and the host is also called the authority.

The following is a URL to a web page whose protocol is HTTP −

https://www.amrood.com/index.htm?language=en#j2se

Notice that this URL does not specify a port, in which case the default port for the protocol is used. With HTTP, the default port is 80.

Constructors

The java.net.URL class represents a URL and has a complete set of methods to manipulate URL in Java.

The URL class has several constructors for creating URLs, including the following −

Sr.No.

Constructors & Description

1

public URL(String protocol, String host, int port, String file) throws MalformedURLException

Creates a URL by putting together the given parts.

2

public URL(String protocol, String host, String file) throws MalformedURLException

Identical to the previous constructor, except that the default port for the given protocol is used.

3

public URL(String url) throws MalformedURLException

Creates a URL from the given String.

4

public URL(URL context, String url) throws MalformedURLException

Creates a URL by parsing together the URL and String arguments.

The URL class contains many methods for accessing the various parts of the URL being represented. Some of the methods in the URL class include the following −

Sr.No.

Method & Description

1

public equals(Object obj)

This method compares this URL for equality with another object.

2

public String getAuthority()

This method returns the authority of the URL.

3

public Object getContent()

This method returns the contents of this URL.

4

public Object getContent(Class<?>[] classes)

This method returns the contents of this URL.

5

public int getDefaultPort()

This method returns the default port for the protocol of the URL.

6

public String getFile()

This method returns the filename of the URL.

7

public String getHost()

This method returns the host of the URL.

8

public String getPath()

This method returns the path of the URL.

9

public int getPort()

This method returns the port of the URL.

10

public String getProtocol()

This method returns the protocol of the URL.

11

public String getQuery()

This method returns the query part of the URL.

12

public String getRef()

This method returns the reference part of the URL.

13

public String getUserInfo()

This method returns the userInfo part of the URL.

14

public int hashCode()

This method creates and return an integer suitable for hash table indexing.

15

public URLConnectionopenConnection()

This method returns a URLConnection instance that represents a connection to the remote object referred to by the URL.

16

public URLConnectionopenConnection(Proxy proxy)

This method acts as openConnection(), except that the connection will be made through the specified proxy; Protocol handlers that do not support proxing will ignore the proxy parameter and make a normal connection.

17

public InputStreamopenStream()

This method opens a connection to this URL and returns an InputStream for reading from that connection.

18

public booleansameFile(URL other)

This method compares two URLs, excluding the fragment component.

19

public static void setURLStreamHandlerFactory(URLStreamHandlerFactoryfac)

This method sets an application's URLStreamHandlerFactory.

20

public String toExternalForm()

This method constructs and return a string representation of this URL.

21

public String toString()

This method constructs and return a string representation of this URL.

22

public String toURI()

This method returns a URI equivalent to this URL.

Advertisement

-PS

Advertisement: 0:02

Example

The following URLDemo program demonstrates the various parts of a URL. A URL is entered on the command line, and the URLDemo program outputs each part of the given URL.

Open Compiler

// File Name : URLDemo.java

import java.io.IOException;

import java.net.URL;

 

public class URLDemo {

 

   public static void main(String [] args) {

      try {

         URL url = new URL("https://www.tutorialspoint.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();

      }

   }

}

A sample run of the this program will produce the following result −

Output

URL is https://www.tutorialspoint.com/index.htm?language=en#j2se

protocol is https

authority is www.tutorialspoint.com

file name is /index.htm?language=en

host is www.tutorialspoint.com

path is /index.htm

port is -1

default port is 443

query is language=en

ref is j2se

URLConnections Class Methods

The openConnection() method returns a java.net.URLConnection, an abstract class whose subclasses represent the various types of URL connections.

For example −

  • If you connect to a URL whose protocol is HTTP, the openConnection() method returns an HttpURLConnection object.
  • If you connect to a URL that represents a JAR file, the openConnection() method returns a JarURLConnection object, etc.

The URLConnection class has many methods for setting or determining information about the connection, including the following −

Sr.No.

Method & Description

1

void addRequestProperty(String key, String value)

Adds a general request property specified by a key-value pair.

2

booleangetAllowUserInteraction()

Returns the value of the allowUserInteraction field for this object.

3

int getConnectTimeout()

Returns setting for connect timeout.

4

Object getContent()

Retrieves the contents of this URL connection.

5

Object getContent(Class[] classes)

Retrieves the contents of this URL connection.

6

String getContentEncoding()

Returns the value of the content-encoding header field.

7

int getContentLength()

Returns the value of the content-length header field.

8

long getContentLengthLong()

Returns the value of the content-length header field as long.

9

String getContentType()

Returns the value of the content-type header field.

10

long getDate()

Returns the value of the date header field.

11

static booleangetDefaultAllowUserInteraction()

Returns the default value of the allowUserInteraction field.

12

booleangetDefaultUseCaches()

Returns the default value of a URLConnection'suseCaches flag.

13

static booleangetDefaultUseCaches(String protocol)

Returns the default value of the useCaches flag for the given protocol.

14

booleangetDoInput()

Returns the value of this URLConnection'sdoInput flag.

15

booleangetDoOutput()

Returns the value of this URLConnection'sdoOutput flag.

16

long getExpiration()

Returns the value of the expires header field.

17

static FileNameMapgetFileNameMap()

Loads filename map (a mimetable) from a data file.

18

String getHeaderField(int n)

Returns the value for the nth header field.

19

String getHeaderField(String name)

Returns the value of the named header field.

20

long getHeaderFieldDate(String name, long Default)

Returns the value of the named field parsed as date.

21

int getHeaderFieldInt(String name, int Default)

Returns the value of the named field parsed as a number.

22

String getHeaderFieldKey(int n)

Returns the key for the nth header field.

23

long getHeaderFieldLong(String name, long Default)

Returns the value of the named field parsed as a number.

24

Map<String,List<String>>getHeaderFields()

Returns an unmodifiable Map of the header fields.

25

long getIfModifiedSince()

Returns the value of this object's ifModifiedSince field.

26

InputStreamgetInputStream()

Returns an input stream that reads from this open connection.

27

int getLastModified()

Returns the value of the last-modified header field.

28

OutputStreamgetOutputStream()

Returns an output stream that writes to this connection.

29

Permission getPermission()

Returns a permission object representing the permission necessary to make the connection represented by this object.

30

int getReadTimeout()

Returns setting for read timeout. 0 return implies that the option is disabled (i.e., timeout of infinity).

31

Map<String,List<String>>getRequestProperties()

Returns an unmodifiable Map of general request properties for this connection.

32

String getRequestProperty(String key)

Returns the value of the named general request property for this connection.

33

URL getURL()

Returns the value of this URLConnection's URL field.

34

booleangetUseCaches()

Returns the value of this URLConnection'suseCaches field.

35

static String guessContentTypeFromName(String fname)

Tries to determine the content type of an object, based on the specified "file" component of a URL.

36

static String guessContentTypeFromStream(InputStream is)

Tries to determine the type of an input stream based on the characters at the beginning of the input stream.

37

void setAllowUserInteraction(booleanallowuserinteraction)

Set the value of the allowUserInteraction field of this URLConnection.

38

void setConnectTimeout(int timeout)

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

39

static void setContentHandlerFactory(ContentHandlerFactoryfac)

Sets the ContentHandlerFactory of an application.

40

static void setDefaultAllowUserInteraction(booleandefaultallowuserinteraction)

Sets the default value of the allowUserInteraction field for all future URLConnection objects to the specified value.

41

void setDefaultUseCaches(booleandefaultusecaches)

Sets the default value of the useCaches field to the specified value.

42

static void setDefaultUseCaches(String protocol, booleandefaultVal)

Sets the default value of the useCaches field for the named protocol to the given value.

43

void setDoInput(booleandoinput)

Sets the value of the doInput field for this URLConnection to the specified value.

44

void setDoOutput(booleandooutput)

Sets the value of the doOutput field for this URLConnection to the specified value.

45

static void setFileNameMap(FileNameMap map)

Sets the FileNameMap.

46

void setIfModifiedSince(long ifmodifiedsince)

Sets the value of the ifModifiedSince field of this URLConnection to the specified value.

47

void setReadTimeout(int timeout)

Sets the read timeout to a specified timeout, in milliseconds.

48

void setRequestProperty(String key, String value)

Sets the general request property.

49

void setUseCaches(booleanusecaches)

Sets the value of the useCaches field of this URLConnection to the specified value.

50

String toString()

Returns a String representation of this URL connection.

Example

The following URLConnectionDemo program connects to a URL entered from the command line.

If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and the data in the resource is read one line at a time.

package com.tutorialspoint;

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLConnection;

 

public class URLConnDemo {

   public static void main(String [] args) {

      try {

         URL url = new URL("https://www.tutorialspoint.com");

URLConnectionurlConnection = url.openConnection();

HttpURLConnection connection = null;

if(urlConnectioninstanceofHttpURLConnection) {

            connection = (HttpURLConnection) urlConnection;

}else {

System.out.println("Please enter an HTTP URL.");

            return;

         }

 

BufferedReader in = new BufferedReader(

            new InputStreamReader(connection.getInputStream()));

         String urlString = "";

         String current;

 

while((current = in.readLine()) != null) {

urlString += current;

         }

System.out.println(urlString);

      } catch (IOException e) {

e.printStackTrace();

      }

   }

}

A sample run of this program will produce the following result −

Output

$ java URLConnDemo

What is a URL?

URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Webpage or FTP directory.

This section shows you how to write Java programs that communicate with a URL. A URL can be broken down into parts, as follows −

protocol://host:port/path?query#ref

Examples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as the filename, and the host is also called the authority.

Example

The following is a URL to a web page whose protocol is HTTP −

https://www.amrood.com/index.htm?language=en#j2se

Notice that this URL does not specify a port, in which case the default port for the protocol is used. With HTTP, the default port is 80.

Java URL Class

The URL class is a part of the java.net package. URL class represents a Uniform Resource Locator (URL). Where, URLs are used for identifying online resources (for example: webpages, images used in the webpages, videos, files, etc.)

The URL class provides several constructors and methods for creating, parsing, and manipulating URLs (or, URL objects).

URL Class Declaration

public final class URL

   extends Object

      implements Serializable

URL Class Constructors

The java.net.URL class represents a URL and has a complete set of methods to manipulate URL in Java.

The URL class has several constructors for creating URLs, including the following −

Sr.No.

Constructors & Description

1

public URL(String protocol, String host, int port, String file) throws MalformedURLException

Creates a URL by putting together the given parts.

2

public URL(String protocol, String host, int port, String file, URLStreamHandler handler) throws MalformedURLException

Creates a URL by putting together the given parts with the specified handler within a specified context.

3

public URL(String protocol, String host, String file) throws MalformedURLException

Identical to the previous constructor, except that the default port for the given protocol is used.

4

public URL(String url) throws MalformedURLException

Creates a URL from the given String.

5

public URL(URL context, String url) throws MalformedURLException

Creates a URL by parsing together the URL and String arguments.

6

public URL(URL context, String url, URLStreamHandler handler) throws MalformedURLException

Creates a URL by parsing together the URL and String arguments with the specified handler within a specified context.

URL Class Methods

The URL class contains many methods for accessing the various parts of the URL being represented. Some of the methods in the URL class include the following −

Sr.No.

Method & Description

1

public equals(Object obj)

This method compares this URL for equality with another object.

2

public String getAuthority()

This method returns the authority of the URL.

3

public Object getContent()

This method returns the contents of this URL.

4

public Object getContent(Class<?>[] classes)

This method returns the contents of this URL.

5

public int getDefaultPort()

This method returns the default port for the protocol of the URL.

6

public String getFile()

This method returns the filename of the URL.

7

public String getHost()

This method returns the host of the URL.

8

public String getPath()

This method returns the path of the URL.

9

public int getPort()

This method returns the port of the URL.

10

public String getProtocol()

This method returns the protocol of the URL.

11

public String getQuery()

This method returns the query part of the URL.

12

public String getRef()

This method returns the reference part of the URL.

13

public String getUserInfo()

This method returns the userInfo part of the URL.

14

public int hashCode()

This method creates and return an integer suitable for hash table indexing.

15

public URLConnectionopenConnection()

This method returns a URLConnection instance that represents a connection to the remote object referred to by the URL.

16

public URLConnectionopenConnection(Proxy proxy)

This method acts as openConnection(), except that the connection will be made through the specified proxy; Protocol handlers that do not support proxing will ignore the proxy parameter and make a normal connection.

17

public InputStreamopenStream()

This method opens a connection to this URL and returns an InputStream for reading from that connection.

18

public booleansameFile(URL other)

This method compares two URLs, excluding the fragment component.

19

public static void setURLStreamHandlerFactory(URLStreamHandlerFactoryfac)

This method sets an application's URLStreamHandlerFactory.

20

public String toExternalForm()

This method constructs and return a string representation of this URL.

21

public String toString()

This method constructs and return a string representation of this URL.

22

public String toURI()

This method returns a URI equivalent to this URL.

  • java.lang.Object

Example of URL Class

The following URLDemo program demonstrates the various parts of a URL. A URL is entered on the command line, and the URLDemo program outputs each part of the given URL.

Open Compiler

// File Name : URLDemo.java

import java.io.IOException;

import java.net.URL;

 

public class URLDemo {

 

   public static void main(String [] args) {

      try {

         URL url = new URL("https://www.tutorialspoint.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();

      }

   }

}

A sample run of the this program will produce the following result −

Output

URL is https://www.tutorialspoint.com/index.htm?language=en#j2se

protocol is https

authority is www.tutorialspoint.com

Java URLConnection Class

java.net.URLConnection, is an abstract class whose subclasses represent the various types of URL connections. Instances of this class can be used both to read from and to write to the resource referenced by the URL.

For example −

  • If you connect to a URL whose protocol is HTTP, the URL.openConnection() method returns an HttpURLConnection object.
  • If you connect to a URL that represents a JAR file, the URL.openConnection() method returns a JarURLConnection object, etc.

Steps to make a connection to a URL

Following are the steps to make a connectiion to the URL and start processing.

  • Invoke URL.openConnection() method to get connection object.
  • Update setup parameters and general request properties as required using connection object various setter methods.
  • Create a connection to remote object using connect() method of connection object.
  • Once remote object is available, access the content/headers of the remote object.

URLConnection Class Declaration

public abstract class URLConnection

   extends Object

URLConnection Class Fields

Sr.No.

Field & Description

1

protected booleanallowUserInteraction

If true, this URL is being examined in a context in which it makes sense to allow user interactions such as popping up an authentication dialog.

2

protected boolean connected

If false, this connection object has not created a communications link to the specified URL.

3

protected booleandoInput

This variable is set by the setDoInput method.

3

protected booleandoOutput

This variable is set by the setDoOutput method.

4

protected long ifModifiedSince

Some protocols support skipping the fetching of the object unless the object has been modified more recently than a certain time.

5

protected URL url

The URL represents the remote object on the World Wide Web to which this connection is opened.

6

protected booleanuseCaches

If true, the protocol is allowed to use caching whenever it can.

URLConnection Class Methods

The URLConnection class has many methods for setting or determining information about the connection, including the following −

Sr.No.

Method & Description

1

void addRequestProperty(String key, String value)

Adds a general request property specified by a key-value pair.

2

booleangetAllowUserInteraction()

Returns the value of the allowUserInteraction field for this object.

3

int getConnectTimeout()

Returns setting for connect timeout.

4

Object getContent()

Retrieves the contents of this URL connection.

5

Object getContent(Class[] classes)

Retrieves the contents of this URL connection.

6

String getContentEncoding()

Returns the value of the content-encoding header field.

7

int getContentLength()

Returns the value of the content-length header field.

8

long getContentLengthLong()

Returns the value of the content-length header field as long.

9

String getContentType()

Returns the value of the content-type header field.

10

long getDate()

Returns the value of the date header field.

11

static booleangetDefaultAllowUserInteraction()

Returns the default value of the allowUserInteraction field.

12

booleangetDefaultUseCaches()

Returns the default value of a URLConnection'suseCaches flag.

13

static booleangetDefaultUseCaches(String protocol)

Returns the default value of the useCaches flag for the given protocol.

14

booleangetDoInput()

Returns the value of this URLConnection'sdoInput flag.

15

booleangetDoOutput()

Returns the value of this URLConnection'sdoOutput flag.

16

long getExpiration()

Returns the value of the expires header field.

17

static FileNameMapgetFileNameMap()

Loads filename map (a mimetable) from a data file.

18

String getHeaderField(int n)

Returns the value for the nth header field.

19

String getHeaderField(String name)

Returns the value of the named header field.

20

long getHeaderFieldDate(String name, long Default)

Returns the value of the named field parsed as date.

21

int getHeaderFieldInt(String name, int Default)

Returns the value of the named field parsed as a number.

22

String getHeaderFieldKey(int n)

Returns the key for the nth header field.

23

long getHeaderFieldLong(String name, long Default)

Returns the value of the named field parsed as a number.

24

Map<String,List<String>>getHeaderFields()

Returns an unmodifiable Map of the header fields.

25

long getIfModifiedSince()

Returns the value of this object's ifModifiedSince field.

26

InputStreamgetInputStream()

Returns an input stream that reads from this open connection.

27

int getLastModified()

Returns the value of the last-modified header field.

28

OutputStreamgetOutputStream()

Returns an output stream that writes to this connection.

29

Permission getPermission()

Returns a permission object representing the permission necessary to make the connection represented by this object.

30

int getReadTimeout()

Returns setting for read timeout. 0 return implies that the option is disabled (i.e., timeout of infinity).

31

Map<String,List<String>>getRequestProperties()

Returns an unmodifiable Map of general request properties for this connection.

32

String getRequestProperty(String key)

Returns the value of the named general request property for this connection.

33

URL getURL()

Returns the value of this URLConnection's URL field.

34

booleangetUseCaches()

Returns the value of this URLConnection'suseCaches field.

35

static String guessContentTypeFromName(String fname)

Tries to determine the content type of an object, based on the specified "file" component of a URL.

36

static String guessContentTypeFromStream(InputStream is)

Tries to determine the type of an input stream based on the characters at the beginning of the input stream.

37

void setAllowUserInteraction(booleanallowuserinteraction)

Set the value of the allowUserInteraction field of this URLConnection.

38

void setConnectTimeout(int timeout)

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

39

static void setContentHandlerFactory(ContentHandlerFactoryfac)

Sets the ContentHandlerFactory of an application.

40

static void setDefaultAllowUserInteraction(booleandefaultallowuserinteraction)

Sets the default value of the allowUserInteraction field for all future URLConnection objects to the specified value.

41

void setDefaultUseCaches(booleandefaultusecaches)

Sets the default value of the useCaches field to the specified value.

42

static void setDefaultUseCaches(String protocol, booleandefaultVal)

Sets the default value of the useCaches field for the named protocol to the given value.

43

void setDoInput(booleandoinput)

Sets the value of the doInput field for this URLConnection to the specified value.

44

void setDoOutput(booleandooutput)

Sets the value of the doOutput field for this URLConnection to the specified value.

45

static void setFileNameMap(FileNameMap map)

Sets the FileNameMap.

46

void setIfModifiedSince(long ifmodifiedsince)

Sets the value of the ifModifiedSince field of this URLConnection to the specified value.

47

void setReadTimeout(int timeout)

Sets the read timeout to a specified timeout, in milliseconds.

48

void setRequestProperty(String key, String value)

Sets the general request property.

49

void setUseCaches(booleanusecaches)

Sets the value of the useCaches field of this URLConnection to the specified value.

50

String toString()

Returns a String representation of this URL connection.

Extends

This class extends following classes

  • java.lang.Object

Example of URLConnection Class Methods

The following URLConnectionDemo program connects to a URL entered from the command line.

If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and the data in the resource is read one line at a time.

package com.tutorialspoint;

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLConnection;

 

public class URLConnectionDemo {

   public static void main(String [] args) {

      try {

         URL url = new URL("https://www.tutorialspoint.com");

URLConnectionurlConnection = url.openConnection();

HttpURLConnection connection = null;

if(urlConnectioninstanceofHttpURLConnection) {

            connection = (HttpURLConnection) urlConnection;

}else {

System.out.println("Please enter an HTTP URL.");

            return;

         }

 

BufferedReader in = new BufferedReader(

            new InputStreamReader(connection.getInputStream()));

         String urlString = "";

         String current;

 

while((current = in.readLine()) != null) {

urlString += current;

         }

System.out.println(urlString);

      } catch (IOException e) {

e.printStackTrace();

      }

   }

}

A sample run of this program will produce the following result −

Output

$ java URLConnectionDemo

 

.....a complete HTML content of home page of tutorialspoint.com.....

 

Java HttpURLConnection Class

java.net.HttpURLConnection, is an abstract class which represents the HTTP-specific URL connection. Instances of this class can be used both to read from and to write to the resource referenced by the URL.

For example −

  • If you connect to a URL whose protocol is HTTP, the URL.openConnection() method returns an HttpURLConnection object.

Steps to make a connection to a URL

Following are the steps to make a connectiion to the URL and start processing.

  • Invoke URL.openConnection() method to get HttpURLConnection object of an HTTP based URL.
  • Update setup parameters and general request properties as required using connection object various setter methods.
  • Create a connection to remote object using connect() method of connection object.
  • Once remote object is available, access the content/headers of the remote object.

HttpURLConnection Class Declaration

public abstract class HttpURLConnection

   extends URLConnection

HttpURLConnection Class Fields

Sr.No.

Field & Description

1

protected int chunkLength

The chunk-length when using chunked encoding streaming mode for output.

2

protected int fixedContentLength

The fixed content-length when using fixed-length streaming mode.

3

protected long fixedContentLengthLong

The fixed content-length when using fixed-length streaming mode.

4

static int HTTP_ACCEPTED

HTTP Status-Code 202: Accepted.

5

static int HTTP_BAD_GATEWAY

HTTP Status-Code 502: Bad Gateway.

6

static int HTTP_BAD_METHOD

HTTP Status-Code 405: Method Not Allowed.

7

static int HTTP_BAD_REQUEST

HTTP Status-Code 400: Bad Request.

8

static int HTTP_CLIENT_TIMEOUT

HTTP Status-Code 408: Request Time-Out.

9

static int HTTP_CONFLICT

HTTP Status-Code 409: Conflict.

10

static int HTTP_CREATED

HTTP Status-Code 201: Created.

11

static int HTTP_ENTITY_TOO_LARGE

HTTP Status-Code 413: Request Entity Too Large.

12

static int HTTP_FORBIDDEN

HTTP Status-Code 403: Forbidden.

13

static int HTTP_GATEWAY_TIMEOUT

HTTP Status-Code 504: Gateway Timeout.

14

static int HTTP_GONE

HTTP Status-Code 410: Gone.

15

static int HTTP_INTERNAL_ERROR

HTTP Status-Code 500: Internal Server Error.

16

static int HTTP_LENGTH_REQUIRED

HTTP Status-Code 411: Length Required.

17

static int HTTP_MOVED_PERM

HTTP Status-Code 301: Moved Permanently.

18

static int HTTP_MOVED_TEMP

HTTP Status-Code 302: Temporary Redirect.

19

static int HTTP_MULT_CHOICE

HTTP Status-Code 300: Multiple Choices.

20

static int HTTP_NO_CONTENT

HTTP Status-Code 204: No Content.

21

static int HTTP_NOT_ACCEPTABLE

HTTP Status-Code 406: Not Acceptable.

22

static int HTTP_NOT_AUTHORITATIVE

HTTP Status-Code 203: Non-Authoritative Information.

23

static int HTTP_NOT_FOUND

HTTP Status-Code 404: Not Found.

24

static int HTTP_NOT_IMPLEMENTED

HTTP Status-Code 501: Not Implemented.

25

static int HTTP_NOT_MODIFIED

HTTP Status-Code 304: Not Modified.

26

static int HTTP_OK

HTTP Status-Code 200: OK.

27

static int HTTP_PARTIAL

HTTP Status-Code 206: Partial Content.

28

static int HTTP_PAYMENT_REQUIRED

HTTP Status-Code 402: Payment Required.

29

static int HTTP_PRECON_FAILED

HTTP Status-Code 412: Precondition Failed.

30

static int HTTP_PROXY_AUTH

HTTP Status-Code 407: Proxy Authentication Required.

31

static int HTTP_REQ_TOO_LONG

HTTP Status-Code 414: Request-URI Too Large.

32

static int HTTP_RESET

HTTP Status-Code 205: Reset Content.

33

static int HTTP_SEE_OTHER

HTTP Status-Code 303: See Other.

34

static int HTTP_UNAUTHORIZED

HTTP Status-Code 401: Unauthorized.

35

static int HTTP_UNAVAILABLE

HTTP Status-Code 503: Service Unavailable.

36

static int HTTP_UNSUPPORTED_TYPE

HTTP Status-Code 415: Unsupported Media Type.

37

static int HTTP_USE_PROXY

HTTP Status-Code 305: Use Proxy.

38

static int HTTP_VERSION

HTTP Status-Code 505: HTTP Version Not Supported.

39

protected booleaninstanceFollowRedirects

If true, the protocol will automatically follow redirects.

40

protected String method

The HTTP method (GET,POST,PUT,etc.).

41

protected int responseCode

An int representing the three digit HTTP Status-Code.

42

protected String responseMessage

The HTTP response message.

HttpURLConnection Class Methods

The HttpURLConnection class has many methods for setting or determining information about the connection, including the following −

Sr.No.

Method & Description

1

abstract void disconnect()

Indicates that other requests to the server are unlikely in the near future.

2

InputStreamgetErrorStream()

Returns the error stream if the connection failed but the server sent useful data nonetheless.

3

static booleangetFollowRedirects()

Returns a boolean indicating whether or not HTTP redirects (3xx) should be automatically followed.

4

String getHeaderField(int n)

Returns the value for the nth header field.

5

String getHeaderFieldKey(int n)

Returns the key for the nth header field.

6

booleangetInstanceFollowRedirects()

Returns the value of this HttpURLConnection'sinstanceFollowRedirects field.

7

Permission getPermission()

Returns a SocketPermission object representing the permission necessary to connect to the destination host and port.

8

String getRequestMethod()

Get the request method.

9

int getResponseCode()

Gets the status code from an HTTP response message.

10

String getResponseMessage()

Gets the HTTP response message, if any, returned along with the response code from a server.

11

void setAuthenticator(Authenticator auth)

Supplies an Authenticator to be used when authentication is requested through the HTTP protocol for this HttpURLConnection.

12

void setChunkedStreamingMode(int chunklen)

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is not known in advance.

13

void setFixedLengthStreamingMode(int contentLength)

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

14

void setFixedLengthStreamingMode(long contentLength)

This method is used to enable streaming of a HTTP request body without internal buffering, when the content length is known in advance.

15

static void setFollowRedirects(boolean set)

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this class.

16

void setInstanceFollowRedirects(booleanfollowRedirects)

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

17

void setRequestMethod(String method)

Set the method for the URL request, one of: GET POST HEAD OPTIONS PUT DELETE TRACE are legal, subject to protocol restrictions.

18

abstract booleanusingProxy()

Indicates if the connection is going through a proxy.

Extends

This class extends following classes

  • java.lang.Object
  • java.net.URLConnection

Example of Java HttpURLConnection Class

The following HttpURLConnection program connects to a URL entered from the command line.

If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and the data in the resource is read one line at a time.

package com.tutorialspoint;

 

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLConnection;

 

public class HttpUrlConnectionDemo {

   public static void main(String [] args) {

      try {

         URL url = new URL("https://www.tutorialspoint.com");

URLConnectionurlConnection = url.openConnection();

HttpURLConnection connection = null;

if(urlConnectioninstanceofHttpURLConnection) {

            connection = (HttpURLConnection) urlConnection;

}else {

System.out.println("Please enter an HTTP URL.");

            return;

         }

 

BufferedReader in = new BufferedReader(

            new InputStreamReader(connection.getInputStream()));

         String urlString = "";

         String current;

 

while((current = in.readLine()) != null) {

urlString += current;

         }

System.out.println(urlString);

      } catch (IOException e) {

e.printStackTrace();

      }

   }

}

A sample run of this program will produce the following result −

Output

$ java HttpURLConnection

 

.....a complete HTML content of home page of tutorialspoint.com.....

 

Comments

Post a Comment

Popular posts from this blog

Syllabus

Unit VI: Interacting with Database