如何通过Spring RestTemplate发送带Raw数据的POST请求
How to Send Raw JSON POST Requests with Spring RestTemplate
Hey there! Let's fix your code first, then break down the proper approach for sending raw JSON data via RestTemplate.
What's Wrong with Your Current Code?
Looking at your snippet, here are the key issues:
- You're trying to use a
MultiValueMap(designed for form-encoded data likex-www-form-urlencoded) instead of sending your JSON object directly as the request body. - You’ve built a
JsonObjectbut aren’t actually passing it as the payload to your POST request. - You’re missing the final step of creating an
HttpEntity(combining headers and body) and executing the request with RestTemplate.
Corrected Code Implementation
Let’s adjust your code to properly send raw JSON. We’ll use javax.json.JsonObject for this example (adjust imports if you’re using Gson or Jackson):
import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import javax.json.Json; import javax.json.JsonObject; // Your existing variables (appId, etc.) should be defined here // 1. Set up headers with JSON content type HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); // 2. Build your raw JSON payload JsonObject properties = Json.createObjectBuilder() .add("app_id", appId) .add("identity", "TestAPI") .add("event", "TestComplete") // Completed the truncated event name // Add any additional properties you need here .build(); // 3. Create HttpEntity combining headers and JSON body HttpEntity<String> requestEntity = new HttpEntity<>(properties.toString(), headers); // 4. Send the POST request using RestTemplate RestTemplate restTemplate = new RestTemplate(); String apiUrl = "https://your-target-api-url.com/endpoint"; // Replace with your actual API URL // Option 1: Get just the response body as a String String responseBody = restTemplate.postForObject(apiUrl, requestEntity, String.class); // Option 2: Get full response details (status code, headers, body) ResponseEntity<String> responseEntity = restTemplate.postForEntity(apiUrl, requestEntity, String.class); System.out.println("Response Status: " + responseEntity.getStatusCode()); System.out.println("Response Body: " + responseEntity.getBody());
Alternative: Using a POJO for Type Safety
For cleaner, more maintainable code (especially with complex payloads), use a POJO (Plain Old Java Object) instead of manual JSON building:
- Create a class representing your payload:
public class EventPayload { private String app_id; private String identity; private String event; // Getters and setters (use Lombok @Data to auto-generate these if you prefer) public String getApp_id() { return app_id; } public void setApp_id(String app_id) { this.app_id = app_id; } public String getIdentity() { return identity; } public void setIdentity(String identity) { this.identity = identity; } public String getEvent() { return event; } public void setEvent(String event) { this.event = event; } }
- Use the POJO in your RestTemplate code:
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); EventPayload payload = new EventPayload(); payload.setApp_id(appId); payload.setIdentity("TestAPI"); payload.setEvent("TestComplete"); HttpEntity<EventPayload> requestEntity = new HttpEntity<>(payload, headers); RestTemplate restTemplate = new RestTemplate(); String apiUrl = "https://your-target-api-url.com/endpoint"; // RestTemplate automatically serializes the POJO to JSON ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, requestEntity, String.class);
Key Takeaways
- When sending raw JSON, don’t use
MultiValueMap—it’s for form data. Instead, pass your JSON (as a String or POJO) directly as the request body. - Always set the
Content-Typeheader toMediaType.APPLICATION_JSONso the server knows to parse the body as JSON. - Use
HttpEntityto wrap your headers and body together before passing to RestTemplate.
内容的提问来源于stack exchange,提问作者Bhargav
相关产品推荐
相关产品推荐

