Java 8 POST request example that sends a JSON payload to a REST
API. I’ll show you both the plain Java HttpURLConnection way and the Spring
Boot RestTemplate way, since you often work with microservices.
🟢 Option 1: Pure Java 8 (HttpURLConnection)
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostRequestExample
{
public
static void main(String[] args) {
try {
// API endpoint
URL url = new
URL("https://jsonplaceholder.typicode.com/posts");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set request method and headers
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/json; utf-8");
conn.setRequestProperty("Accept",
"application/json");
conn.setDoOutput(true);
// JSON payload
String jsonInputString = "{
\"title\": \"Java POST\", \"body\": \"Hello
from Java\", \"userId\": 1 }";
// Write JSON to request body
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
// Read response
try (java.io.BufferedReader br = new java.io.BufferedReader(
new java.io.InputStreamReader(conn.getInputStream(),
"utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("Response: " + response.toString());
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
🟢 Option 2: Spring Boot (RestTemplate)
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
public class PostRequestSpringExample {
public
static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "https://jsonplaceholder.typicode.com/posts";
//
JSON payload
String jsonPayload = "{ \"title\": \"Spring
POST\", \"body\": \"Hello from Spring Boot\",
\"userId\": 2 }";
//
Set headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//
Wrap payload + headers
HttpEntity<String> request = new
HttpEntity<>(jsonPayload, headers);
// Send POST
request
String response = restTemplate.postForObject(url, request,
String.class);
System.out.println("Response: " + response);
}
}
🔑 Key Points
- conn.setDoOutput(true) → enables sending a request
body in HttpURLConnection.
- Always set Content-Type:
application/json.
- In Spring Boot, RestTemplate.postForObject() makes it much simpler.
- For real-world microservices,
you’d typically send a Java object instead of raw JSON, and let
Spring handle serialization.
No comments:
Post a Comment