URLhandling
URLhandling
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.*;
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.*;
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
SERVER SIDE
import java.net.*;
import java.io.*;
// Close resources
reader.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
(Client):
import java.net.*;
import java.io.*;
writer.println("Hello, server!");
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Udp SERVER
import java.net.*;
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
UDP CLIENT
import java.net.*;