To implement a simple HTTP client using HttpURLConnection
in Java, you can follow the steps below. HttpURLConnection
is part of the java.net
package and is used to communicate with HTTP servers. Here’s how to create a basic HTTP client:
Steps
- Create a URL Object: Specify the target URI as a
URL
object. - Open a Connection: Use the
openConnection()
method of theURL
object to obtain anHttpURLConnection
. - Set Request Properties: Configure request types (GET, POST, etc.), headers, and other properties.
- Send the Request: Connect to the server and send the request.
- Read the Response: Read the server’s response using an input stream.
- Handle Exceptions: Properly handle
IO
ornetwork
exceptions. - Close Resources: Always close connection and streams properly.
Example Code: HTTP GET Request
Here’s an example of an HTTP GET request using HttpURLConnection
:
package org.kodejava.net;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class SimpleHttpClient {
public static void main(String[] args) {
String urlString = "https://jsonplaceholder.typicode.com/posts/1"; // Example API endpoint
HttpURLConnection connection = null;
try {
// Create URL object
URL url = new URL(urlString);
// Open connection
connection = (HttpURLConnection) url.openConnection();
// Set the request method to GET
connection.setRequestMethod("GET");
// Set request headers (optional)
connection.setRequestProperty("Accept", "application/json");
// Connect to the server (optional as getInputStream implies connect())
connection.connect();
// Validate the response code
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // HTTP 200
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Print the response
System.out.println("Response: " + response.toString());
} else {
System.out.println("HTTP Error: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace(); // Handle exceptions
} finally {
if (connection != null) {
connection.disconnect(); // Close the connection
}
}
}
}
Example Code: HTTP POST Request
Below is an example of sending data via an HTTP POST request:
package org.kodejava.net;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class SimpleHttpPostClient {
public static void main(String[] args) {
String urlString = "https://jsonplaceholder.typicode.com/posts"; // Example API endpoint
HttpURLConnection connection = null;
try {
// Create URL object
URL url = new URL(urlString);
// Open connection
connection = (HttpURLConnection) url.openConnection();
// Set the request method to POST
connection.setRequestMethod("POST");
// Set request headers
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json");
// Enable writing output to the connection
connection.setDoOutput(true);
// JSON body for the POST request
String jsonInputString = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
// Write data to output stream
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// Validate the response code
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_CREATED) { // HTTP 201
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Print the response
System.out.println("Response: " + response.toString());
} else {
System.out.println("HTTP Error: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace(); // Handle exceptions
} finally {
if (connection != null) {
connection.disconnect(); // Close the connection
}
}
}
}
Key Points to Consider:
- Thread Safety:
HttpURLConnection
is not thread-safe, so don’t use it across multiple threads. - Time-Outs: Always configure connection and read timeouts using
setConnectTimeout()
andsetReadTimeout()
to avoid hanging requests. - Resource Management: Always close streams and disconnect the connection to release resources properly.
- Error Handling: Handle different HTTP error codes (
4xx
,5xx
) gracefully.
For production-ready applications, you might want to consider alternatives like the Apache HttpClient or the Java HttpClient
introduced in Java 11, which provides a modern and simpler API.