Java provides classes in the java.net package to work with web resources. The URL and HttpURLConnection classes allow Java programs to connect to web servers, send requests, and receive responses.
Represents the address of a resource on the Internet
Syntax:
http → Hypertext Transfer Protocol
https → Secure HTTP
ftp → File Transfer Protocol
Output:
Note:
Port -1means the default port is used for the protocol.
Subclass of URLConnection for HTTP connections
Allows sending GET, POST, PUT, DELETE requests
Can read HTTP response codes, headers, and content
Create a URL object
Open a connection using openConnection()
Set request method (GET, POST)
Read response code and content
Close the connection
Output:
Prints the HTTP response code (e.g., 200)
Prints the HTML content of the page
setDoOutput(true) enables sending data in POST requests
Can read response similarly using BufferedReader
| Method | Purpose |
|---|---|
setRequestMethod(String method) | Sets HTTP method (GET, POST, etc.) |
getResponseCode() | Returns HTTP status code |
getInputStream() | Reads server response |
getOutputStream() | Sends data to server (POST/PUT) |
disconnect() | Closes the connection |
Platform-independent HTTP client support
Supports GET, POST, PUT, DELETE requests
Can read headers, cookies, and response codes
Easy integration with REST APIs and web services
Always close streams and disconnect after communication
Use HTTPS for secure connections
HttpURLConnection is suitable for low-level HTTP requests
For advanced usage, consider HttpClient (Java 11+)
URL and HttpURLConnection classes in Java provide powerful tools to interact with web resources. Mastery of these classes enables Java applications to perform web requests, consume APIs, and implement client-server communication efficiently.
Take quizzes related to this topic and see where you stand!
Start Quiz Now