Chapter 4
Chapter 4
Archana Gopnarayan
Lecturer , Department of Information Technology (NBA Accrediated)
Vidyalankar Polytechnic
InetAddres
• The InetAddress class is used to encapsulate both the numerical IP address and the
domain name for that address.
int getPort( ) Returns the remote port to which the invoking Socket object is connected. It
returns 0 if the socket is not connected.
int getLocalPort( ) Returns the local port to which the invoking Socket object is bound. It
returns –1 if the socket is not bound.
• We can gain access to the input and output streams associated with a Socket by
use of the getInputStream( ) and getOuptutStream( ) methods.
• Each can throw an IOException if the socket has been invalidated by a loss of
connection.
• These streams are used to send and receive data.
int getContentLength( ) Returns the size in bytes of the content associated with the
resource. If the length is unavailable, –1 is returned.
String getContentType( ) Returns the type of content found in the resource. Returns null
if the content type is not available.
long getDate( ) Returns the time and date of the response
long getExpiration( ) Returns the expiration time and date of the resource represented
in terms of milliseconds Zero is returned if the expiration date is unavailable.
Map<String, List<String>>getHeaderFields( ) Returns a map that contains all of the
header fields and values.
import java.net.*;
import java.io.*;
import java.util.Date;
class UCDemo
{
public static void main(String args[]) throws Exception
{
int c;
URL hp = new URL("http://www.internic.net");
URLConnection hpCon = hp.openConnection();
long d = hpCon.getDate();
if(d==0)
System.out.println("No date information.");
else
System.out.println("Date: " + new Date(d));
System.out.println("Content-Type: " + hpCon.getContentType());
d = hpCon.getExpiration();
if(d==0)
System.out.println("No expiration information.");
else
System.out.println("Expires: " + new Date(d));
d = hpCon.getLastModified();
if(d==0)
System.out.println("No last-modified information.");
else
System.out.println("Last-Modified: " + new Date(d));
int len = hpCon.getContentLength();
if(len == -1)
System.out.println("Content length unavailable.");
else
System.out.println("Content-Length: " + len);
if(len != 0) {
System.out.println("=== Content ===");
InputStream input = hpCon.getInputStream();
int i = len;
while (((c = input.read()) != -1))
{
System.out.print((char) c);
}
input.close();
}
else {
System.out.println("No content available.");
}
}
}
HttpURLConnection
• Java provides a subclass of URLConnection that provides support for HTTP
connections. This class is called HttpURLConnection.
• String getRequestMethod( ) Returns a string representing how URL requests are made.
The default is GET. Other options, such as POST, are available.