HttpURLConnection is a Java networking class used to send HTTP requests and receive HTTP responses from web servers or REST APIs.
In simple words:
HttpURLConnection helps Java applications communicate with websites, REST APIs, microservices, and external servers using HTTP and HTTPS protocols.
Why HttpURLConnection is Important?
Modern enterprise applications constantly interact with:
- REST APIs
- Payment gateways
- Cloud services
- Microservices
- Authentication servers
- Third-party integrations
- Distributed systems
HttpURLConnection Overview Diagram
Java Application
|
v
HttpURLConnection
|
v
HTTP/HTTPS Request
|
v
Web Server / REST API
|
v
HTTP Response Returned
Main Package
java.net
Inheritance Hierarchy
URLConnection
|
v
HttpURLConnection
What Protocols Does it Support?
- HTTP
- HTTPS
Why HttpURLConnection is Widely Used?
- Built into Java
- No external libraries needed
- Supports REST communication
- Supports request headers
- Supports GET and POST requests
- Supports secure HTTPS communication
How HttpURLConnection Works Internally?
URL Created
|
v
Connection Opened
|
v
HTTP Request Sent
|
v
Server Processes Request
|
v
HTTP Response Returned
Basic Steps to Use HttpURLConnection
- Create URL object
- Open connection
- Cast to HttpURLConnection
- Set request method
- Send request
- Read response
- Close resources
Basic GET Request Example
import java.net.*;
import java.io.*;
URL url =
new URL(
"https://jsonplaceholder.typicode.com/posts/1"
);
HttpURLConnection connection =
(HttpURLConnection)
url.openConnection();
connection.setRequestMethod(
"GET"
);
BufferedReader br =
new BufferedReader(
new InputStreamReader(
connection.getInputStream()
)
);
String line;
while(
(line = br.readLine()) != null
) {
System.out.println(line);
}
br.close();
connection.disconnect();
Internal GET Request Flow
Client Creates Request
|
v
HTTP GET Sent
|
v
Server Returns Response
|
v
InputStream Reads Response
What is setRequestMethod()?
Used to specify HTTP method type.
Common HTTP Methods
| Method | Purpose |
|---|---|
| GET | Fetch data |
| POST | Create data |
| PUT | Update data |
| DELETE | Delete data |
POST Request Example
URL url =
new URL(
"https://example.com/api"
);
HttpURLConnection connection =
(HttpURLConnection)
url.openConnection();
connection.setRequestMethod(
"POST"
);
connection.setDoOutput(true);
OutputStream os =
connection.getOutputStream();
String data =
"{ \"name\": \"Naresh\" }";
os.write(
data.getBytes()
);
os.flush();
os.close();
POST Request Flow
Application Creates JSON Data
|
v
HttpURLConnection Sends POST Request
|
v
Server Processes Request
|
v
Response Returned
What is getInputStream()?
Used to read successful server responses.
What is getErrorStream()?
Used to read error responses from server.
Error Handling Example
int status =
connection.getResponseCode();
InputStream is;
if(status >= 200 &&
status < 300) {
is =
connection.getInputStream();
}
else {
is =
connection.getErrorStream();
}
HTTP Response Codes
| Status Code | Meaning |
|---|---|
| 200 | Success |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 404 | Not Found |
| 500 | Internal Server Error |
How to Set Headers?
connection.setRequestProperty(
"Content-Type",
"application/json"
);
connection.setRequestProperty(
"Authorization",
"Bearer token"
);
Header Flow
Application Adds Headers
|
v
Headers Sent with HTTP Request
|
v
Server Uses Header Information
Setting Timeouts
connection.setConnectTimeout(
5000
);
connection.setReadTimeout(
5000
);
Why Timeouts Important?
Prevents applications from hanging forever if server does not respond.
HTTPS Communication
HttpURLConnection also supports secure HTTPS communication.
HTTPS Flow
HTTPS Request Sent
|
v
SSL/TLS Handshake Happens
|
v
Encrypted Communication Established
Difference Between URLConnection and HttpURLConnection
| Feature | URLConnection | HttpURLConnection |
|---|---|---|
| Purpose | General Connection | HTTP-Specific Communication |
| Protocols | Multiple | HTTP/HTTPS |
| HTTP Methods | No | Supports GET/POST/etc. |
| Status Codes | No | Yes |
HttpURLConnection in Banking Systems
Banking applications use HttpURLConnection for:
- Payment gateway integration
- Transaction verification
- Fraud detection APIs
- KYC verification services
- Third-party banking APIs
Banking Flow
Customer Makes Payment
|
v
HttpURLConnection Sends API Request
|
v
Banking Server Validates Transaction
|
v
Secure Response Returned
HttpURLConnection in E-Commerce Systems
E-commerce platforms use it for:
- Shipping APIs
- Payment integrations
- Inventory systems
- Currency conversion APIs
- Vendor integrations
E-Commerce Flow
Customer Places Order
|
v
API Request Sent to Shipping Service
|
v
Tracking Details Returned
HttpURLConnection in Spring Boot
Spring Boot internally uses HTTP communication concepts through:
- RestTemplate
- WebClient
- Feign Clients
- Reactive WebFlux
Spring Boot REST Flow
Spring Service Calls External API
|
v
HTTP Request Generated
|
v
External Service Responds
|
v
Data Converted into Java Object
HttpURLConnection in Microservices
Microservices architectures use HTTP communication heavily for:
- REST APIs
- Distributed communication
- API gateways
- Cloud-native services
- Service orchestration
Microservice Flow
Service A Sends HTTP Request
|
v
HttpURLConnection Opens Connection
|
v
Service B Processes Request
|
v
Response Returned
Advantages of HttpURLConnection
- Built into Java
- No external dependencies
- Supports HTTP and HTTPS
- Supports headers and authentication
- Good for basic API communication
Disadvantages
- Verbose code
- Low-level API
- Difficult asynchronous handling
- Harder JSON mapping
- Less flexible than modern clients
Modern Alternatives
- RestTemplate
- WebClient
- OkHttp
- Apache HttpClient
- Feign Client
Common Interview Mistake
Many developers think HttpURLConnection automatically converts JSON into Java objects.
Actually:
- It only transfers raw data.
- JSON parsing must be handled separately.
Another Common Mistake
Many developers think disconnect() closes streams automatically.
Actually:
- Streams should still be closed properly.
Best Practices
- Always close streams properly
- Use try-with-resources
- Set connection timeouts
- Handle error streams carefully
- Use HTTPS for secure communication
- Validate API responses properly
Realtime Enterprise Example
Online Payment Gateway Integration
Customer Initiates Payment
|
v
HttpURLConnection Sends HTTPS Request
|
v
Payment Gateway Processes Transaction
|
v
Secure Response Returned
|
v
Payment Status Updated
Related Learning Topics
- What is URL and URLConnection in Java
- What is Java Networking
- What is REST API
- What is Socket Programming in Java
- What is Spring Boot
- What are Microservices
Professional Interview Answer
HttpURLConnection is a Java networking class used for HTTP and HTTPS communication between Java applications and remote servers or REST APIs. It is a subclass of URLConnection and provides methods for sending HTTP requests such as GET, POST, PUT, and DELETE, setting request headers, handling response codes, managing input and output streams, configuring timeouts, and processing HTTP responses. HttpURLConnection is widely used for API integrations, payment gateways, cloud services, distributed microservices, REST communication, banking platforms, e-commerce systems, and external service orchestration. Modern frameworks such as Spring Boot RestTemplate, WebClient, Feign clients, reactive WebFlux systems, API gateways, and cloud-native architectures internally build upon similar HTTP communication concepts. Although modern HTTP clients provide more advanced features, HttpURLConnection remains an important foundational Java networking API for understanding HTTP communication internals.
Frequently Asked Questions
What is HttpURLConnection in Java?
It is a Java class used for HTTP and HTTPS communication.
Which package contains HttpURLConnection?
java.net package.
Can HttpURLConnection send POST requests?
Yes, it supports GET, POST, PUT, DELETE, and other HTTP methods.
Does HttpURLConnection support HTTPS?
Yes, it supports secure HTTPS communication.
Where is HttpURLConnection used?
REST APIs, payment gateways, Spring Boot systems, microservices, and cloud integrations.