You are on page 1of 55

Java Network Programming

Java Networking

• Computer Network means a group of computers connect with


each other via some medium and transfer data between them
as and when require.
• Java supports Network Programming so we can make such
program in which the machines connected in network will
send and receive data from other machine in the network by
programming.
• The first and simple logic to send or receive any kind of data
or message is we must have the address of receiver or sender.
• So when a computer needs to communicate with another
computer, it`s require the other computer’s address.
Java Networking Terminology
• The widely used java networking terminologies are given
below:
• IP Address
• Protocol
• Port Number
• MAC Address
• Connection-oriented and connection-less protocol
• Socket
Java Networking Terminology
1) IP Address
IP address is a unique number assigned to a node of a network e.g.
192.168.0.1 .
It is composed of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication.
For example:
TCP
FTP
Telnet
SMTP
POP etc.
Java Networking Terminology
3) Port Number
Data transmitted over the internet is accompanied by addressing information
that identifies the computer and the port for which it is destined.
The port number is used to uniquely identify different applications. It acts as
a communication endpoint between applications.
The port number is associated with the IP address for communication
between two applications.
The port numbers ranging from 0
to 1023 are restricted; They are
reserved for use by well-known
services such as HTTP and FTP
and other system services.
Java Networking Terminology
4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC
(Network Interface Controller). A network node can have multiple NIC
but each with unique MAC.
5) Connection-oriented and connection-less protocol
In connection-oriented protocol, acknowledgement is sent by the
receiver. So it is reliable but slow. The example of connection-oriented
protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the
receiver. So it is not reliable but fast. The example of connection-less
protocol is UDP.
6) Socket
A socket is an endpoint between two way communication.
Internet Addressing
• Every computer on the internet has an address. This address is
a number that uniquely identifies each computer on the net.

• IP (short for Internet Protocol) specifies the technical format of


packets and the addressing scheme for computers to
communicate over a network. Most networks combine IP with
a higher-level protocol called Transmission Control Protocol
(TCP), which establishes a virtual connection between a
destination and a source.

• For IP addressing, in Java three classes are provided:


– Inetaddress
– Inet4address
– Inet6address
IP version 4 Addresses
(Inet4address)
• 32 bit unsigned integers
– possible values 0 - 4,294,967,295
• Typically written as a “dotted quad of octets”
– four 8 bit values with a range of 0-255 separated by “.”
– For example, 202.12.28.129 can be written as below

202 . 12 . 28 . 129

1 1 0 0 1 0 1 0 0 0 0 0 1 1 0 0 0 0 1 1 1 0 0 0 1 0 0 0 0 0 0 1
IP version 6 Addresses
(Inet6address)
• 128- bit unsigned integers
• Hexadecimal Notation:
3FFE:F200:0234:AB00:0123:4567:8901:ABCD

• IPv6 is designed to solve many of the problems of IPv4,


including mobility, auto-configuration, and overall
extensibility.
• IPv6 expands the address space on the Internet and
supports a nearly unlimited number of devices that can
be directly connected to the Internet.
Address types
• Unicast : An identifier for a single interface. A packet sent to a
unicast address is delivered to the interface identified by that
address. It is used for one-to-one communication.
– The Unspecified Address -- Also called anylocal or wildcard
address. It must never be assigned to any node. It indicates the
absence of an address. One example of its use is as the target
of bind, which allows a server to accept a client connection on
any interface, in case the server host has multiple interfaces.
The unspecified address must not be used as the destination
address of an IP packet.
– The Loopback Addresses -- This is the address assigned to
the loopback interface. Anything sent to this IP address loops
around and becomes IP input on the local host. This address is
often used when testing a client. (127.0.0.1)
• Multicast: An identifier for a set of interfaces (typically belonging to
different nodes). A packet sent to a multicast address is delivered to
all interfaces identified by that address. It is used for one-to-many
communications. IPv4 multicast addresses range from 224.0.0.0 through
239.255.255.255.
• Broadcast: Assigned to all network interfaces located on a subnet
on the network and used for one-to-everyone-on-a-subnet
communications.
IP address scope

• Link-local addresses are designed to be used for


addressing on a single link for purposes such as auto-
address configuration, neighbor discovery, or when
no routers are present.
• Site-local addresses are designed to be used for
addressing inside of a site without the need for a
global prefix.
• Global addresses are unique across the internet.
InetAddress Class

• Java InetAddress Class is used to encapsulate the two thing.


1. Numeric IP Address
2. The domain name for that address

• It has no visible constructors so to create its object, the user have


to use one of the available in-built static methods. The
commonly used InetAddress in-built methods are:

• (1) getLocalHost(): It returns the InetAddress object that


represents the local host contain the name and address both. If
this method unable to find out the host name, it throw an
UnknownHostException.
• Syntax: Static InetAddress getLocalHost() throws
UnknownHostException
InetAddress Class

• (2) getByName(): It returns an InetAddress for a host name passed to it


as a parameter argument. If this method unable to find out the host name,
it throw an UnknownHostException.
• Syntax:
Static InetAddress getByName(String host_name) throws UnknownHostException

• (3) getAllByName(): It returns an array of an InetAddress that represent


all of the addresses that a particular name resolve to it. If this method
can’t find out the name to at least one address, it throw an
UnknownHostException.
• Syntax:
Static InetAddress[] getAllByName(String host_name) throws
UnknownHostException
InetAddress Class
static InetAddress[] getAllByName(String host)
Given the name of a host, returns an array of its IP addresses, based on the configured name service on
the system.
static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address .
static InetAddress getByName(String host)
Determines the IP address of a host, given the host's name.
String getCanonicalHostName()
Gets the fully qualified domain name for this IP address.
String getHostAddress()
Returns the IP address string in textual presentation.
String getHostName()
Gets the host name for this IP address.
static InetAddress getLocalHost()
Returns the local host.
boolean isAnyLocalAddress()
Utility routine to check if the InetAddress in a wildcard address.
boolean isLinkLocalAddress()
Utility routine to check if the InetAddress is an link local address.
boolean isLoopbackAddress()
Utility routine to check if the InetAddress is a loopback address.
boolean isMulticastAddress()
Utility routine to check if the InetAddress is an IP multicast address.
boolean isSiteLocalAddress()
Utility routine to check if the InetAddress is a site local address.
InetAddress Example
import java.net.*;
class myAddress { /* Output :

public static void main (String args[]) { C:\xxx>java myAddress


try {
InetAddress address = InetAddress.getLocalHost();
F1T1/100.100.102.11
System.out.println(address);
System.out.println(address.getAddress()); [B@3e25a5
byte[] myadd=address.getAddress();
System.out.println(address.getByAddress(myadd)); /100.100.102.11
System.out.println(InetAddress.getByName("F1T1")); F1T1/100.100.102.11
System.out.println(address.getCanonicalHostName()); F1T1.SVITFILESER.COM
System.out.println(address.getHostAddress()); 100.100.102.11
System.out.println(address.getHostName()); F1T1
}
catch (UnknownHostException e) { */
System.out.println("Could not find this computer's
address.");
}
}
}
InetAddress Example
// Demonstrate InetAddress.

import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("starwave.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}
Basics of Networking (cont..)

• Network programming involves two types of


programs
– Client Program
– Server Program

• Server Program is a program that provides


services to one or more users who run client
programs to access those services.
Basics of Networking

• Computers running on the Internet communicate


to each other using either the Transmission
Control Protocol (TCP) or the User Datagram
Protocol (UDP).

• Classes in java.net package are used to write


Java programs that communicate over the
network.
TCP

• TCP is a connection-based protocol, guarantees


that data sent from one end of the connection
actually gets to the other end and in the same
order it was sent.
• HTTP, FTP and Telnet are all examples of
applications that require reliable communication
channel.
• When HTTP is used to read from a URL, the
data must be received in the order in which it
was sent. Otherwise, you end up with a jumbled
HTML file.
UDP

• UDP is not connection-based like TCP.


• It sends independent packets of data
called datagrams, from one application to
another.
• Here, the order of delivery is not important
and is not guaranteed, and each message
is independent of any other.
Some ports have been reserved to
support common/well known services:
Socket and Socket-based Communication
• Sockets provide an interface for programming networks
at the transport layer.
• A server (program) runs on a specific computer and has
a socket that is bound to a specific port.
• The server listens to the socket for a client to make a
connection request.
• If everything goes well, the server accepts the
connection.
• Upon acceptance, the server gets a new socket bound to
a different port.
• It needs a new socket (consequently a different port
number) so that it can continue to listen to the original
socket for connection requests while serving the
connected client.
SOCKET PROGRAMMING AND java.net CLASS

• A socket is an endpoint of a two-way communication link between two


programs running on the network.
• Socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent.
• Java provides a set of classes, defined in a package called java.net, to
enable the rapid development of network applications.
• Key classes in java.net package simplifying the complexity involved in
creating client and server programs are:

• ContentHandler * DatagramPacket
• DatagramSocket * DatagramSocketImpl
• HttpURLConnection * InetAddress
• MulticastSocket *ServerSocket
• Socket *SocketImpl
• URL *URLConnection
• URLEncoder *URLStreamHandler
TCP/IP SOCKET PROGRAMMING
• The two key classes from the java.net package
used in creation of server and client programs
are:
– ServerSocket
– Socket
• A server program creates a specific type of
socket that is used to listen for client requests
(server socket).
• In the case of a connection request, the program
creates a new socket through which it will
exchange data with the client using input and
output streams.
TCP/IP SOCKET PROGRAMMING
ServerSocket class
• 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:
SN Methods with Description
1 public ServerSocket(int port) throws IOExceptionAttempts 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 IOExceptionSimilar 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
IOExceptionSimilar 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 IOExceptionCreates an unbound server socket.


When using this constructor, use the bind() method when you are ready to bind
the server socket
ServerSocket class methods
SN Methods with 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
instantiated the ServerSocket using the no-argument constructor.
Socket class
• The java.net.Socket class represents the socket that both the client
and 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.

SN Methods with 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 IOExceptionThis method is
identical to the previous constructor, except that the host is denoted by an
InetAddress object.
3 public Socket(String host, int port, InetAddress localAddress, 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, InetAddress localAddress, 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.
Socket class methods
SN Methods with Description
1 public void connect(SocketAddress host, int timeout) throws IOExceptionThis
method connects the socket to the specified host. This method is needed only when
you instantiated the Socket using the no-argument constructor.

2 public InetAddress getInetAddress()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 SocketAddress getRemoteSocketAddress()Returns the address of the
remote socket.
6 public InputStream getInputStream() throws IOExceptionReturns the input stream
of the socket. The input stream is connected to the output stream of the remote socket.

7 public OutputStream getOutputStream() throws IOExceptionReturns the output


stream of the socket. The output stream is connected to the input stream of the remote
socket
8 public void close() throws IOExceptionCloses the socket, which makes this Socket
object no longer capable of connecting again to any server
A simple Server Program in Java
1. Open the Server Socket:
ServerSocket server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
DataInputStream is = new
DataInputStream(client.getInputStream());
DataOutputStream os = new
DataOutputStream(client.getOutputStream());
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes(“Hello\n”);
5. Close socket:
client.close();
A simple Client Program in Java
1. Create a Socket Object:
Socket client = new Socket(server, port_id);
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());
3. Perform I/O or communication with the server:
Receive data from the server: String line = is.readLine();
Send data to the server: os.writeBytes(“Hello\n”);
4. Close the socket when done:
client.close();
Echo Server (Example)
import java.io.*;
import java.net.*;
public class EchoServer {
private static final int BUFFER_SIZE = 256;
private static int listenPort = 4444;
public static void main(String[] args) throws Exception
{
ServerSocket serverSock = new ServerSocket(listenPort);
System.out.println("listening on port "+listenPort);
Socket sock = serverSock.accept();
System.out.println("new connection " + sock);

BufferedReader r = new BufferedReader(new InputStreamReader(sock.getInputStream()));


PrintWriter w = new PrintWriter(sock.getOutputStream(), true);

String msg=new String();


while(( msg=r.readLine())!= null)
{
System.out.println("echoing "+msg);
if (msg.equals(“bye"))
break;

w.println(msg);
}
r.close(); w.close(); sock.close(); serverSock.close();
}
}
Echo Client (Example)
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) {
try { Socket s = new Socket("127.0.0.1", 4444);

BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));


PrintWriter w = new PrintWriter(s.getOutputStream(), true);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));

String line;
do { line = r.readLine();
if ( line != null )
System.out.println(line);
line = con.readLine();
w.println(line);
} while ( !line.trim().equals("bye") );
} catch (Exception err) { System.err.println(err); } } }
UDP SOCKET PROGRAMMING
• Datagram packets are used to implement a connectionless packet
delivery service supported by the UDP protocol.
• Each message is transferred from source machine to destination
based on information contained within that packet.
• That means, each packet needs to have destination address and
each packet might be routed differently, and might arrive in any
order.
• Packet delivery is not guaranteed.
• The format of datagram packet is:
| Msg | length | Host | serverPort |
• Java supports datagram communication through the following
classes:
– DatagramPacket
– DatagramSocket
UDP SOCKET PROGRAMMING

• The class DatagramPacket contains several constructors that can be used


for creating packet object.
• One of them is:
• DatagramPacket(byte[] buf, int length, InetAddress address, int port);
• This constructor is used for creating a datagram packet for sending packets
of length length to the specified port number on the specified host. The
message to be transmitted is indicated in the first argument.
• The key methods of DatagramPacket class are:
• byte[] getData()- Returns the data buffer.
• int getLength() - Returns the length of the data to be sent or the length of
the data received.
• void setData(byte[] buf)- Sets the data buffer for this packet.
• void setLength(int length)- Sets the length for this packet.
• The class DatagramSocket supports various methods that can be used for
transmitting or receiving data a datagram over the network. The two key
methods are:
• void send(DatagramPacket p) - Sends a datagram packet from this socket.
• void receive(DatagramPacket p)- Receives a datagram packet from this
socket.
DatagramSocket class
• Java DatagramSocket class represents a connection-less socket
for sending and receiving datagram packets.
• A datagram is basically an information but there is no guarantee of
its content, arrival or arrival time.

• Constructors of DatagramSocket class :

• DatagramSocket() throws SocketEeption: it creates a datagram


socket and binds it with the available Port Number on the localhost
machine.
• DatagramSocket(int port) throws SocketEeption: it creates a
datagram socket and binds it with the given Port Number.
• DatagramSocket(int port, InetAddress address) throws
SocketEeption: it creates a datagram socket and binds it with the
specified port number and host address.
DatagramSocket class methods
• close()Closes this datagram socket.
• getLocalAddress()Gets the local address to which the
socket is bound.
• getLocalPort()Returns the port number on the local host
to which this socket is bound.
• getSoTimeout()Retrive setting for SO_TIMEOUT.
• receive(DatagramPacket)Receives a datagram packet
from this socket.
• send(DatagramPacket)Sends a datagram packet from
this socket.
• setSoTimeout(int)Enable/disable SO_TIMEOUT with
the specified timeout, in milliseconds.
DatagramPacket Class
• Java DatagramPacket is a message that can be sent or received. If
you send multiple packet, it may arrive in any order. Additionally,
packet delivery is not guaranteed.

• Constructors of DatagramPacket class :

• DatagramPacket(byte[] barr, int length): it creates a datagram


packet. This constructor is used to receive the packets.
• DatagramPacket(byte[] barr, int length, InetAddress address,
int port): it creates a datagram packet. This constructor is used to
send the packets.
DatagramPacket Class methods
• getAddress()Returns the IP address of the machine to
which this datagram is being sent or from which the
datagram was received.
• getData()Returns the data received or the data to be
sent.
• getLength()Returns the length of the data to be sent or
the length of the data received.
• getPort()Returns the port number on the remote host to
which this datagram is being sent or from which the
datagram was received.
• setAddress(InetAddress)
• setData(byte[])
• setLength(int)
• setPort(int)
UDP Server Program
// UDPServer.java: A simple UDP server program.
import java.net.*;
import java.io.*;
public class UDPServer {
public static void main(String args[]){
DatagramSocket aSocket = null;
if (args.length < 1) {
System.out.println(“Usage: java UDPServer <Port Number>”);
System.exit(1);
}
int socket_no = Integer.valueOf(args[0]).intValue();
aSocket = new DatagramSocket(socket_no);
byte[] buffer = new byte[1000];
while(true) {
DatagramPacket request = new DatagramPacket(buffer,
buffer.length);
aSocket.receive(request);
DatagramPacket reply = new DatagramPacket(request.getData(),
request.getLength(),request.getAddress(),
request.getPort());
aSocket.send(reply);
}
}
}
UDP Client Program
import java.net.*;
import java.io.*;
public class UDPClient {
public static void main(String args[]){
// args give message contents and server hostname
DatagramSocket aSocket = null;
if (args.length < 3) {
System.out.println(“Usage: java UDPClient <message> <Host name> <Port number>”);
System.exit(1);
}
try {
aSocket = new DatagramSocket();
byte [] m = args[0].getBytes();
InetAddress aHost = InetAddress.getByName(args[1]);
int serverPort = Integer.valueOf(args[2]).intValue();
DatagramPacket request =
new DatagramPacket(m, args[0].length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
System.out.println(“Reply: ” + new String(reply.getData()));
}
Server communicating to multiple Clients

• How a server can communicate to multiple


clients?
• Problem with constructing such a server
– Need to use threads because otherwise
clients will be queued up waiting for a
connection.
Multi-threaded Socket-based echo server

public class EchoServer2 extends Thread


{
protected Socket clientSocket;

public static void main(String[] args) throws IOException


{
ServerSocket serverSocket = null;

serverSocket = new ServerSocket(10008);


System.out.println ("Connection Socket Created");
while (true)
{
System.out.println ("Waiting for Connection");
new EchoServer2 (serverSocket.accept());
}
}
private EchoServer2 (Socket clientSoc)
{
clientSocket = clientSoc;
start();
}
Multi-threaded Socket-based echo server (Conti…)
public void run()
{
System.out.println ("New Communication Thread Started");

try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine;

while ((inputLine = in.readLine()) != null)


{
System.out.println ("Server: " + inputLine);
out.println(inputLine);

if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
}
catch (IOException e) {
System.err.println("Problem with Communication Server");
System.exit(1); }
}
}
URL Class
• URLs identify a resource & its address information anywhere
on the Internet.
• URL is based on four components
– The protocol (e.g. http, ftp)
– Host name/ IP address of the host ( e.g. java.sun.com)
– Port number (optional. Default port for http is 80)
– The actual file path
– For example,
– http//ww.javatpoint.com:80/sonoojaiswal/
• A URL can be broken down into parts, as follows −
• protocol://host:port/path?query#ref
Commonly used methods of Java URL class

Method Description

public String getProtocol() it returns the protocol of the


URL.
public String getHost() it returns the host name of
the URL.
public String getPort() it returns the Port Number
of the URL.
public String getFile() it returns the file name of
the URL.
public URLConnection it returns the instance of
openConnection() URLConnection i.e.
associated with this URL.
Example of Java URL class
//URLDemo.java
import java.io.*;
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.svit.com/java-tutorial");

System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
Output:
Protocol: http
}catch(Exception e){System.out.println(e);}
Host Name: www.svit.com
} Port Number: -1
} File Name: /java-tutorial
Example of Java URL class

import java.net.*;
import java.io.*;

public class URLDemo2


{
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()); Output:
System.out.println("path is " + url.getPath());
URL is http://www.amrood.com/index.htm?language=en#j2se
System.out.println("port is " + url.getPort()); protocol is http
System.out.println("default port is " + url.getDefaultPort()); authority is www.amrood.com
System.out.println("query is " + url.getQuery()); file name is /index.htm?language=en
System.out.println("ref is " + url.getRef()); host is www.amrood.com
path is /index.htm
}catch(IOException e)
port is -1
{ default port is 80
e.printStackTrace(); query is language=en
} ref is j2se
}
}
URLConnection Class
• The openConnection() method of URL class 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...
URLConnection Class Methods:
SN Methods with Description
1 Object getContent()
Retrieves the contents of this URL connection.
2 Object getContent(Class[] classes)
Retrieves the contents of this URL connection.
3 String getContentEncoding()
Returns the value of the content-encoding header field.
4 int getContentLength()
Returns the value of the content-length header field.
5 String getContentType()
Returns the value of the content-type header field.
6 int getLastModified()
Returns the value of the last-modified header field.
7 long getExpiration()
Returns the value of the expires header field.
8 long getIfModifiedSince()
Returns the value of this object's ifModifiedSince field.
URLConnection Class Methods:
SN Methods with Description
9 public void setDoInput(boolean input)
Passes in true to denote that the connection will be used for input.
The default value is true because clients typically read from a
URLConnection.
10 public void setDoOutput(boolean output)
Passes in true to denote that the connection will be used for output.
The default value is false because many types of URLs do not support
being written to.
11 public InputStream getInputStream() throws IOException
Returns the input stream of the URL connection for reading from the
resource.
12 public OutputStream getOutputStream() throws IOException
Returns the output stream of the URL connection for writing to the
resource
13 public URL getURL()
Returns the URL that this URLConnection object is connected to
URLConnection class Example
// File Name : URLConnDemo.java
import java.net.*;
import java.io.*;
public class URLConnDemo {

public static void main(String [] args)


{
try { URL url = new URL("http://www.amrood.com");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection)
{ 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;
Output:
while((current = in.readLine()) != null)
{ urlString += current; } .....a complete HTML content of
System.out.println(urlString); home page of amrood.com.....
}catch(IOException e)
{ e.printStackTrace(); }
}}

You might also like