URL and HttpURLConnection in Java
⏱ Estimated reading time: 3 min
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.
1. URL (Uniform Resource Locator)
-
Represents the address of a resource on the Internet
-
Syntax:
Common Protocols
-
http→ Hypertext Transfer Protocol -
https→ Secure HTTP -
ftp→ File Transfer Protocol
URL Example
Output:
Note:
Port -1means the default port is used for the protocol.
2. HttpURLConnection
-
Subclass of
URLConnectionfor HTTP connections -
Allows sending GET, POST, PUT, DELETE requests
-
Can read HTTP response codes, headers, and content
Steps to Use HttpURLConnection
-
Create a URL object
-
Open a connection using
openConnection() -
Set request method (
GET,POST) -
Read response code and content
-
Close the connection
3. Example: HTTP GET Request
Output:
-
Prints the HTTP response code (e.g.,
200) -
Prints the HTML content of the page
4. Example: HTTP POST Request
-
setDoOutput(true)enables sending data in POST requests -
Can read response similarly using
BufferedReader
5. Key Methods in HttpURLConnection
| 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 |
6. Advantages
-
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
7. Key Points
-
Always close streams and disconnect after communication
-
Use HTTPS for secure connections
-
HttpURLConnectionis suitable for low-level HTTP requests -
For advanced usage, consider HttpClient (Java 11+)
8. Conclusion
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.
Register Now
Share this Post
← Back to Tutorials