Getting URL contents



After you create a URL, you will probably want to fetch contents. The easiest way to do this is by calling the getContent method

public final Object getContent()

This first method requires that you define a content handler for the content returned by the URL

The following example dumps the content of a URL to the System.out.stream by opening an input stream to the URL and reading one byte at a time.

Example

import java.net.*;

import java.io.*;
class Example1
{
public static void main(String args[]0
{
try {
URL url=new URL(getDocumentBase(),”main.html”);
InputStream in=url.openStream();
int b;
while(b=in.read()!=-1)
{
System.out.println((char)b);
} catch(Exception e)
{ System.out.println(“Exception Due to –>”+e);
e.printStackTrace();
}

Getting URL Information

You can retrieve the specific pieces of URL using the following methods

public String getProtocol()
public String getHost()
public String getPort()
public String getFile()

Share with SociBook.com

Random Posts

Post a Comment