[JAVA-26374-spring-resttemplate] Moved "RestTemplate Post Request wit… (#15104)

* [JAVA-26374-spring-resttemplate] Moved "RestTemplate Post Request with JSON" to spring-resttemplate-1

* [JAVA-26374] Moved "Get and Post Lists of Objects with RestTemplate" article to spring-resttemplate-1
This commit is contained in:
panos-kakos
2023-11-22 10:28:23 +00:00
committed by GitHub
parent aff7d722b1
commit c23f0d6b1f
22 changed files with 69 additions and 13 deletions
@@ -0,0 +1,16 @@
package com.baeldung.resttemplate;
import java.util.Collections;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(RestTemplateApplication.class);
app.setDefaultProperties(Collections.singletonMap("server.servlet.encoding.charset", "ISO-8859-1"));
app.run(args);
}
}
@@ -0,0 +1,12 @@
package com.baeldung.resttemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestTemplateConfigurationApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateConfigurationApplication.class, args);
}
}
@@ -0,0 +1,16 @@
package com.baeldung.resttemplate.lists;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Sample application used to demonstrate working with Lists and RestTemplate.
*/
@SpringBootApplication
public class EmployeeApplication
{
public static void main(String[] args)
{
SpringApplication.run(EmployeeApplication.class, args);
}
}
@@ -0,0 +1,121 @@
package com.baeldung.resttemplate.lists.client;
import static java.util.Arrays.asList;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.baeldung.resttemplate.lists.dto.Employee;
import com.baeldung.resttemplate.lists.dto.EmployeeList;
/**
* Application that shows how to use Lists with RestTemplate.
*/
public class EmployeeClient {
public static void main(String[] args) {
EmployeeClient employeeClient = new EmployeeClient();
System.out.println("Calling GET for entity using arrays");
employeeClient.getForEntityEmployeesAsArray();
System.out.println("Calling GET using ParameterizedTypeReference");
employeeClient.getAllEmployeesUsingParameterizedTypeReference();
System.out.println("Calling GET using wrapper class");
employeeClient.getAllEmployeesUsingWrapperClass();
System.out.println("Calling POST using normal lists");
employeeClient.createEmployeesUsingLists();
System.out.println("Calling POST using wrapper class");
employeeClient.createEmployeesUsingWrapperClass();
}
public EmployeeClient() {
}
public Employee[] getForEntityEmployeesAsArray() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Employee[]> response =
restTemplate.getForEntity(
"http://localhost:8082/spring-rest/employees/",
Employee[].class);
Employee[] employees = response.getBody();
assert employees != null;
asList(employees).forEach(System.out::println);
return employees;
}
public List<Employee> getAllEmployeesUsingParameterizedTypeReference() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Employee>> response =
restTemplate.exchange(
"http://localhost:8082/spring-rest/employees/",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<Employee>>() {
});
List<Employee> employees = response.getBody();
assert employees != null;
employees.forEach(System.out::println);
return employees;
}
public List<Employee> getAllEmployeesUsingWrapperClass() {
RestTemplate restTemplate = new RestTemplate();
EmployeeList response =
restTemplate.getForObject(
"http://localhost:8082/spring-rest/employees/v2",
EmployeeList.class);
List<Employee> employees = response.getEmployees();
employees.forEach(System.out::println);
return employees;
}
public void createEmployeesUsingLists() {
RestTemplate restTemplate = new RestTemplate();
List<Employee> newEmployees = new ArrayList<>();
newEmployees.add(new Employee(3, "Intern"));
newEmployees.add(new Employee(4, "CEO"));
restTemplate.postForObject(
"http://localhost:8082/spring-rest/employees/",
newEmployees,
ResponseEntity.class);
}
public void createEmployeesUsingWrapperClass() {
RestTemplate restTemplate = new RestTemplate();
List<Employee> newEmployees = new ArrayList<>();
newEmployees.add(new Employee(3, "Intern"));
newEmployees.add(new Employee(4, "CEO"));
restTemplate.postForObject(
"http://localhost:8082/spring-rest/employees/v2/",
new EmployeeList(newEmployees),
ResponseEntity.class);
}
}
@@ -0,0 +1,46 @@
package com.baeldung.resttemplate.lists.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.resttemplate.lists.dto.Employee;
import com.baeldung.resttemplate.lists.dto.EmployeeList;
import com.baeldung.resttemplate.lists.service.EmployeeService;
@RestController
@RequestMapping("/employees")
public class EmployeeResource
{
@Autowired
private EmployeeService employeeService;
@RequestMapping(method = RequestMethod.GET, path = "/")
public List<Employee> getEmployees()
{
return employeeService.getAllEmployees();
}
@RequestMapping(method = RequestMethod.GET, path = "/v2")
public EmployeeList getEmployeesUsingWrapperClass()
{
List<Employee> employees = employeeService.getAllEmployees();
return new EmployeeList(employees);
}
@RequestMapping(method = RequestMethod.POST, path = "/")
public void addEmployees(@RequestBody List<Employee> employees)
{
employeeService.addEmployees(employees);
}
@RequestMapping(method = RequestMethod.POST, path = "/v2")
public void addEmployeesUsingWrapperClass(@RequestBody EmployeeList employeeWrapper)
{
employeeService.addEmployees(employeeWrapper.getEmployees());
}
}
@@ -0,0 +1,40 @@
package com.baeldung.resttemplate.lists.dto;
public class Employee {
public long id;
public String title;
public Employee()
{
}
public Employee(long id, String title)
{
this.id = id;
this.title = title;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString()
{
return "Employee #" + id + "[" + title + "]";
}
}
@@ -0,0 +1,29 @@
package com.baeldung.resttemplate.lists.dto;
import java.util.ArrayList;
import java.util.List;
public class EmployeeList
{
public List<Employee> employees;
public EmployeeList()
{
employees = new ArrayList<>();
}
public EmployeeList(List<Employee> employees)
{
this.employees = employees;
}
public void setEmployees(List<Employee> employees)
{
this.employees = employees;
}
public List<Employee> getEmployees()
{
return employees;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.resttemplate.lists.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baeldung.resttemplate.lists.dto.Employee;
@Service("EmployeeListService")
public class EmployeeService
{
public List<Employee> getAllEmployees()
{
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1, "Manager"));
employees.add(new Employee(2, "Java Developer"));
return employees;
}
public void addEmployees(List<Employee> employees)
{
employees.forEach(e -> System.out.println("Adding new employee " + e));
}
}
@@ -0,0 +1,38 @@
package com.baeldung.resttemplate.web.controller;
import javax.servlet.http.HttpServletResponse;
import com.baeldung.resttemplate.web.service.PersonService;
import com.baeldung.resttemplate.web.dto.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController
public class PersonAPI {
@Autowired
private PersonService personService;
@GetMapping("/")
public String home() {
return "Spring boot is working!";
}
@PostMapping(value = "/createPerson", consumes = "application/json", produces = "application/json")
public Person createPerson(@RequestBody Person person) {
return personService.saveUpdatePerson(person);
}
@PostMapping(value = "/updatePerson", consumes = "application/json", produces = "application/json")
public Person updatePerson(@RequestBody Person person, HttpServletResponse response) {
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/findPerson/" + person.getId())
.toUriString());
return personService.saveUpdatePerson(person);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.resttemplate.web.dto;
public class Person {
private Integer id;
private String name;
public Person() {
}
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.resttemplate.web.service;
import com.baeldung.resttemplate.web.dto.Person;
public interface PersonService {
public Person saveUpdatePerson(Person person);
public Person findPersonById(Integer id);
}
@@ -0,0 +1,19 @@
package com.baeldung.resttemplate.web.service;
import com.baeldung.resttemplate.web.dto.Person;
import org.springframework.stereotype.Component;
@Component
public class PersonServiceImpl implements PersonService {
@Override
public Person saveUpdatePerson(Person person) {
return person;
}
@Override
public Person findPersonById(Integer id) {
return new Person(id, "John");
}
}
@@ -0,0 +1,2 @@
server.port=8080
server.servlet.context-path=/spring-rest
@@ -0,0 +1,97 @@
package com.baeldung.resttemplate.postjson;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.net.URI;
import com.baeldung.resttemplate.RestTemplateConfigurationApplication;
import com.baeldung.resttemplate.web.dto.Person;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RestTemplateConfigurationApplication.class)
public class PersonAPILiveTest {
private static String createPersonUrl;
private static String updatePersonUrl;
private static RestTemplate restTemplate;
private static HttpHeaders headers;
private final ObjectMapper objectMapper = new ObjectMapper();
private static JSONObject personJsonObject;
@BeforeClass
public static void runBeforeAllTestMethods() throws JSONException {
createPersonUrl = "http://localhost:8082/spring-rest/createPerson";
updatePersonUrl = "http://localhost:8082/spring-rest/updatePerson";
restTemplate = new RestTemplate();
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
personJsonObject = new JSONObject();
personJsonObject.put("id", 1);
personJsonObject.put("name", "John");
}
@Test
public void givenDataIsJson_whenDataIsPostedByPostForObject_thenResponseBodyIsNotNull() throws IOException {
HttpEntity<String> request = new HttpEntity<String>(personJsonObject.toString(), headers);
String personResultAsJsonStr = restTemplate.postForObject(createPersonUrl, request, String.class);
JsonNode root = objectMapper.readTree(personResultAsJsonStr);
Person person = restTemplate.postForObject(createPersonUrl, request, Person.class);
assertNotNull(personResultAsJsonStr);
assertNotNull(root);
assertNotNull(root.path("name")
.asText());
assertNotNull(person);
assertNotNull(person.getName());
}
@Test
public void givenDataIsJson_whenDataIsPostedByPostForEntity_thenResponseBodyIsNotNull() throws IOException {
HttpEntity<String> request = new HttpEntity<String>(personJsonObject.toString(), headers);
ResponseEntity<String> responseEntityStr = restTemplate.postForEntity(createPersonUrl, request, String.class);
JsonNode root = objectMapper.readTree(responseEntityStr.getBody());
ResponseEntity<Person> responseEntityPerson = restTemplate.postForEntity(createPersonUrl, request, Person.class);
assertNotNull(responseEntityStr.getBody());
assertNotNull(root.path("name")
.asText());
assertNotNull(responseEntityPerson.getBody());
assertNotNull(responseEntityPerson.getBody()
.getName());
}
@Test
public void givenDataIsJson_whenDataIsPostedByPostForLocation_thenResponseBodyIsTheLocationHeader() throws JsonProcessingException {
HttpEntity<String> request = new HttpEntity<String>(personJsonObject.toString(), headers);
URI locationHeader = restTemplate.postForLocation(updatePersonUrl, request);
assertNotNull(locationHeader);
}
}
@@ -0,0 +1,59 @@
package com.baeldung.resttemplate.postjson;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import org.json.JSONException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import com.baeldung.resttemplate.RestTemplateApplication;
import com.baeldung.resttemplate.web.dto.Person;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RestTemplateApplication.class)
public class RestTemplatePostRequestEncodingLiveTest {
private static String createPersonUrl;
private static RestTemplate restTemplate;
@BeforeClass
public static void runBeforeAllTestMethods() throws JSONException {
createPersonUrl = "http://localhost:8080/spring-rest/createPerson";
restTemplate = new RestTemplate();
}
@Test
public void givenJapaneseNameInDataWithoutHeaderEncoding_whenDataIsPostedByPostForObject_thenSaveIncorrectly() {
Person japanese = new Person(100, "関連当");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Person> request = new HttpEntity<>(japanese, headers);
Person person = restTemplate.postForObject(createPersonUrl, request, Person.class);
assertNotNull(person);
assertNotEquals("関連当", person.getName());
}
@Test
public void givenJapaneseNameInDataWithHeaderEncoding_whenDataIsPostedByPostForObject_thenSaveCorrectly() {
Person japanese = new Person(100, "関連当");
HttpHeaders headers = new HttpHeaders();
headers.set("Content-type", "application/json;charset=UTF-8");
HttpEntity<Person> request = new HttpEntity<>(japanese, headers);
Person person = restTemplate.postForObject(createPersonUrl, request, Person.class);
assertNotNull(person);
assertEquals("関連当", person.getName());
}
}
@@ -0,0 +1,5 @@
logging.level.org.springframework.web.client.RestTemplate=DEBUG
logging.level.com.baeldung.resttemplate.logging=DEBUG
logging.level.org.apache.http=DEBUG
logging.level.httpclient.wire=DEBUG
logging.pattern.console=%20logger{20} - %msg%n
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>