0% found this document useful (0 votes)
4 views

Practical No. 15

The document contains practical examples of Java code that demonstrate how to work with URLs and URIs. It includes displaying parts of a URL, determining supported protocols, and reading content from a URL. Each section provides code snippets and outlines the expected outputs.

Uploaded by

khanzainab6002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Practical No. 15

The document contains practical examples of Java code that demonstrate how to work with URLs and URIs. It includes displaying parts of a URL, determining supported protocols, and reading content from a URL. Each section provides code snippets and outlines the expected outputs.

Uploaded by

khanzainab6002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Practical No.

15
1. Display the parts of a URL
import java.net.*;
public class Test {
public static void main(String[] args) {
try {
URI uri = new URI("http", "www.yahoo.com", "/index", null);
URL hp = uri.toURL();
System.out.println(hp.getProtocol());
System.out.println(hp.getPath());
System.out.println(hp.getHost());
System.out.println(hp.getFile());
System.out.println(hp.getPort());
} catch (URISyntaxException | MalformedURLException e) {
System.out.println(e); Output:
}
}
}

2. Determining which protocols your machine supports


import java.net.*;
public class WindowDemo {
public static void testProtocol(String url) {
try {
URI uri = new URI(url);
URL u = uri.toURL();
System.out.println(u.getProtocol() + " is supported");
} catch (URISyntaxException | MalformedURLException e) {
System.out.println("Invalid URL: " + url);
}
}
public static void main(String[] arg) {
testProtocol("http://www.adc.org");
testProtocol("https://www.xyz.com/");
testProtocol("ftp://msbte.org/languages/java/javafaq/");
testProtocol("mailto:[email protected]");
testProtocol("telnet://msbte.org/");
testProtocol("file:///etc/passwd");
}
Output:
}
3. Read the content from a URL
import java.net.*;
import java.io.*;
public class Demo {
public static void main(String[] arg) {
try {
URI uri = new URI("http://www.google.com");
URL url = uri.toURL(); // Convert URI to URL
URLConnection con = url.openConnection();
InputStream stream = con.getInputStream();
int i;
while ((i = stream.read()) != -1) {
System.out.print((char) i);
}
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:

You might also like