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

URLhandling

The document provides an overview of URL handling in Java, detailing key classes such as URL, URLConnection, HttpURLConnection, Socket, and DatagramSocket for network programming. It includes examples demonstrating how to use these classes for HTTP communication, socket programming, and UDP communication. Additionally, it mentions other important classes like InetAddress and MulticastSocket for handling IP addresses and multicast communication.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

URLhandling

The document provides an overview of URL handling in Java, detailing key classes such as URL, URLConnection, HttpURLConnection, Socket, and DatagramSocket for network programming. It includes examples demonstrating how to use these classes for HTTP communication, socket programming, and UDP communication. Additionally, it mentions other important classes like InetAddress and MulticastSocket for handling IP addresses and multicast communication.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

URL HANDLING IN JAVA

Urlclass in java and all the necessary classes required for network programming
In Java, network programming involves a variety of classes, particularly when dealing with internet-
based communication (e.g., web content retrieval, socket communication, etc.). One of the important
classes for accessing URLs is the URL class. Along with it, there are several other classes provided by
the java.net package, which are necessary for network programming.

1. URL Class
The URL (Uniform Resource Locator) class in Java represents a resource on the web, such as a file,
image, or web page, which is accessible via HTTP, HTTPS, FTP, etc. This class allows you to create an
object that represents the URL, open a connection to the resource, and read its content.
Key Methods in URL Class:
URL(String url): This constructor creates a URL object from the specified string representation of the
URL.
openStream(): Opens a connection to the resource referenced by the URL and returns an
InputStream for reading from the resource.
openConnection(): Opens a connection to the resource referenced by the URL and returns a
URLConnection object.
getHost(): Returns the host name of the URL.
getPort(): Returns the port number of the URL, or -1 if no port is explicitly specified.
Example Usage:
import java.net.*;
import java.io.*;

public class URLExample {


public static void main(String[] args) {
try {
// Create a URL object pointing to a website
URL url = new URL("https://www.example.com");

// Open a stream to the resource


InputStream in = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

// Read content from the URL


String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

// Close the resources


reader.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. URLConnection Class
The URLConnection class represents a communication link between the application and a URL. You
can use this class to send requests and get responses from the server.
Key Methods in URLConnection Class:
connect(): Opens a connection to the URL.
getInputStream(): Returns an InputStream to read data from the resource.
getOutputStream(): Returns an OutputStream to send data to the resource.
setRequestProperty(String key, String value): Sets a general request property (like User-Agent).
getHeaderField(String name): Gets the value of the named header field.
import java.net.*;
import java.io.*;

public class URLConnectionExample {


public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection();

// Open the connection and get the input stream


InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

reader.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

3. HttpURLConnection Class
The HttpURLConnection class is a subclass of URLConnection and is used to send HTTP requests (GET,
POST, etc.) and handle HTTP responses.
Key Methods in HttpURLConnection Class:
setRequestMethod(String method): Sets the HTTP request method (GET, POST, PUT, etc.).
getResponseCode(): Returns the HTTP response code from the server (e.g., 200 for success, 404 for
not found).
getInputStream(): Returns an InputStream for reading the response body.
getOutputStream(): Returns an OutputStream for writing request data in case of POST or PUT
methods.

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

public class HttpURLConnectionExample {


public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");

int responseCode = connection.getResponseCode();


System.out.println("Response Code: " + responseCode);

// Read the response


BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}

reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

4. Socket and ServerSocket Classes


The Socket class is used for communication between a client and a server, while the ServerSocket
class is used to set up a server that waits for incoming connections.
Key Methods in Socket Class:
getInputStream(): Returns an InputStream for reading data from the server.
getOutputStream(): Returns an OutputStream for sending data to the server.
close(): Closes the socket.
Key Methods in ServerSocket Class:
accept(): Waits for a connection from a client and returns a Socket object.
close(): Closes the server socket.

SERVER SIDE

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

public class Server {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(7777);
System.out.println("Server is listening on port 7777...");

Socket socket = serverSocket.accept();


System.out.println("Client connected.");

// Read message from the client


BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
String message = reader.readLine();
System.out.println("Client says: " + message);

// Close resources
reader.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

(Client):

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

public class Client {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 7777);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

writer.println("Hello, server!");
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

5. DatagramSocket and DatagramPacket Classes (For UDP Communication)


DatagramSocket and DatagramPacket classes are used to send and receive UDP packets. Unlike TCP
sockets, UDP is connectionless and doesn't guarantee message delivery.
Key Methods in DatagramSocket Class:
send(DatagramPacket p): Sends a UDP packet.
receive(DatagramPacket p): Receives a UDP packet.
close(): Closes the socket.
Key Methods in DatagramPacket Class:
getData(): Returns the data buffer.
getAddress(): Returns the IP address of the sender.
getPort(): Returns the port number of the sender.

Udp SERVER

import java.net.*;

public class UDPServer {


public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket(9876);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

System.out.println("Server is waiting for a message...");


socket.receive(packet);

String message = new String(packet.getData(), 0, packet.getLength());


System.out.println("Client says: " + message);

socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

UDP CLIENT
import java.net.*;

public class UDPClient {


public static void main(String[] args) {
try {
DatagramSocket socket = new DatagramSocket();
byte[] buffer = "Hello, UDP server!".getBytes();
InetAddress address = InetAddress.getByName("localhost");

DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 9876);


socket.send(packet);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

6. Other Key Classes in Network Programming:


InetAddress: Represents an IP address. It can be used to resolve hostnames into IP addresses and
vice versa.
getByName(String host): Returns an InetAddress object based on the provided hostname.
getHostAddress(): Returns the IP address in string form.
getHostName(): Returns the hostname associated with the IP address.
MulticastSocket: A subclass

You might also like