Spring Boot
1. Ejemplo visto en: https://artifactsbyrake.blogspot.com/2021/02/resttemplate-patch.html
Definiendo un @Bean de RestTemplate
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
Usando HttpComponentsClientHttpRequestFactory, esto como una mejora del código de arriba.
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
restTemplate.setRequestFactory(requestFactory);
return restTemplate;
}
Inyectando el @Bean, usualmente en el Controller.
@Autowire
private RestTemplate restTemplate;
Haciendo uso de restTemplate.
String objRecuperado = restTemplate.exchange("http://localhost:8080/users", HttpMethod.POST, httpEntity, String.class);
2. Consumir Servicio Spring Boot + JWT con JAVA. Ejemplo visto en http://jambrocio.blogspot.com/2019/09/consumir-servicio-spring-boot-jwt.html
Consumidor.java
package com.util;
import java.nio.charset.Charset;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
public class Consumidor {
static final String URL_LOGIN = "http://192.168.20.64:8071/oauth/token";
public static void main(String[] args) {
String usernameHeader = "angularapp";
String passwordHeader = "12345";
String usernameBody = "42596272";
String passwordBody = "12345";
postLogin(usernameHeader, passwordHeader, usernameBody, passwordBody);
}
private static void postLogin(String usernameHeader, String passwordHeader, String usernameBody, String passwordBody) {
// Request Header
HttpHeaders headers = new HttpHeaders();
headers = createHeaders(usernameHeader, passwordHeader);
// Request Body
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.add("username", usernameBody);
body.add("password", passwordBody);
body.add("grant_type", "password");
// Request Entity
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);
// RestTemplate
RestTemplate restTemplate = new RestTemplate();
// POST Login
ResponseEntity<String> response = restTemplate.exchange(URL_LOGIN, HttpMethod.POST, requestEntity, String.class);
HttpHeaders responseHeaders = response.getHeaders();
String responseBody = response.getBody();
String responseStatus = String.valueOf(response.getStatusCodeValue());
System.out.println("Status : " + responseStatus);
System.out.println("Body : " + responseBody);
}
private static HttpHeaders createHeaders(String username, String password){
return new HttpHeaders() {{
String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(Charset.forName("US-ASCII")) );
String authHeader = "Basic " + new String( encodedAuth );
set( "Authorization", authHeader );
}};
}
}
The LaxRedirectStrategy allows us to redirect in case of HEAD, GET, POST, DELETE.
Método GET
RestTemplate restTemplate = new RestTemplate();
ResponseEntitymybean<MyBean>response = restTemplate.getForEntity("webservice endPoint url", MyBean.class);
Método POST.
final RestTemplate restTemplate = new RestTemplate();
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
final HttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy())
.build();
factory.setHttpClient(httpClient);
restTemplate.setRequestFactory(factory);
Map<String, String> params = new HashMap<String, String>();
params.put("email", "yourname@gmail.com");
ResponseEntity response = restTemplate.postForEntity(""webservice endPoint url"", params, String.class);
UserControllerTest
package main;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.Collections;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
@RunWith (SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration (classes = Config.class)
@WebAppConfiguration
@IntegrationTest
public class UserControllerTest
{
final String BASE_URL = "http://localhost:9999/customer/";
@Test
public void shouldCreateNewUser() {
final String USER_NAME = "Leif Ericson";
final String USER_ADDRESS = "Vinland";
User user = new User();
user.setName(USER_NAME);
user.setAddress(USER_ADDRESS);
RestTemplate rest = new TestRestTemplate();
ResponseEntity<User> response =
rest.postForEntity(BASE_URL, user, User.class, Collections.EMPTY_MAP);
assertThat( response.getStatusCode() , equalTo(HttpStatus.CREATED));
User userCreated = response.getBody();
assertThat( userCreated.getId() , notNullValue() );
assertThat( userCreated.getName() , equalTo(CUSTOMER_NAME) );
assertThat( userCreated.getAddress() , equalTo(CUSTOMER_ADDRESS) );
}
@Test
public void shouldFailToGetUnknownUser()
throws IOException {
final int UNKNOWN_ID = Integer.MAX_VALUE;
final String EXPECTED_ANSWER_MESSAGE = "user with id : '" + UNKNOWN_ID+ "' does not exist";
RestTemplate rest = new TestRestTemplate();
ResponseEntity<String> response = rest.getForEntity(BASE_URL + UNKNOWN_ID, String.class);
assertThat( response.getStatusCode() , equalTo(HttpStatus.NOT_FOUND));
ObjectMapper objectMapper = new ObjectMapper();
JsonNode responseJson = objectMapper.readTree(response.getBody());
JsonNode messageJson = responseJson.path("message");
assertThat( messageJson.isMissingNode() , is(false) );
assertThat( messageJson.asText() , equalTo(EXPECTED_ANSWER_MESSAGE) );
}
}
5. Ejemplo visto en http://lkonopski.blogspot.com/2012/05/using-spring-resttemplate-with.html
Usando GET
String pong = new RestTemplate().getForObject(address + PING, String.class);
Validate.isTrue(PONG.equals(pong));
Usando POST
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity req = new HttpEntity<>(urlEncodeYourParams(), headers);
RestTemplate rest = new RestTemplate();
ResponseEntity result = rest.postForEntity(address, req, String.class);
System.out.println( result.getBody() );
6. Ejemplo visto en https://www.slmanju.com/2018/01/spring-generic-resttemplate.html
private RestTemplateHelper restTemplateHelper;
// other codes...
// find by id
UserDto userDto = restTemplateHelper.getForEntity(UserDto.class, "http://localhost:8080/users/{id}", id);
// find all
UserDto userDto = restTemplateHelper.getForList(UserDto.class, "http://localhost:8080/users");
// save
UserDto userDto = restTemplateHelper.postForEntity(UserDto.class, "http://localhost:8080/users", userDto);
// update
UserDto userDto = restTemplateHelper.putForEntity(UserDto.class, "http://localhost:8080/users/{id}", userDto, id);
// delete
restTemplateHelper.delete("http://localhost:8080/users/{id}", id);
7. Ejemplo visto en https://sunitkatkar.blogspot.com/2017/11/spring-boot-resttemplate-to-call.html
@RestResource(urlMapping = '/Account/*')
global with sharing class MyRestResource {
@HttpGet
global static List<Account> getAccounts() {
List<Account> result = [SELECT Id, Name, Phone, Website FROM Account LIMIT 2];
return result;
}
}
8. Ejemplo visto en https://javarevisited.blogspot.com/2022/03/how-to-send-json-via-post-request-using.html
Student.java
package com.school.model;
public class Student {
private String firstName;
private String lastName;
private int age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
StudentRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository < Student, Integer > {
Student findById(int id);
}
IStudentService.java
import java.util.List;
public interface IStudentService {
Student saveStudent(Student student);
Student getStudentById(Integer id);
}
StudentServiceImpl.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class StudentServiceImpl implements IStudentService {
@Autowired
StudentRepository studentRepository;
//add a new student to h2 database
@Override
public String saveStudent(Cards card) {
try {
studentRepository.save(card);
return "Saved to database successfully !";
} catch (Exception e) {
e.printStackTrace();
return "Error in saving the value";
}
}
//get the specific student from the h2 database
@Override
public Student getStudentById(String cardNumber) {
return studentRepository.findById(cardNumber);
}
}
StudentController.java
@Controller
public class StudentController {
@Autowired
StudentServiceImpl studentService;
@PostMapping(
value = "/addstudent", consumes = "application/json", produces = "application/json")
public Person createPerson(@RequestBody Student student) {
return studentService.saveStudent(student);
}
@PostMapping(
value = "/updatestudent", consumes = "application/json",
produces = "application/json")
public Student updateStudent(@RequestBody Student student,
HttpServletResponse response) {
response.setHeader("Location", ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/findStudent/" + student.getId()).toUriString());
return studentService.saveStudent(student);
}
}
Usando @BeforeClass
@BeforeClass
public static void runBeforeAllTestMethods() {
createPersonUrl = "http://localhost:8080/addstudent";
updatePersonUrl = "http://localhost:8080/updatestudent";
restTemplate = new RestTemplate();
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JsonObjectStudent = new JSONObject();
JsonObjectStudent.put("id", 1);
JsonObjectStudent.put("name", "John");
}
Usando @Test
@Test
public void postforEnityMethod()
throws IOException {
HttpEntity < String > request =
new HttpEntity < String > (.toString(), headers);
ResponseEntity < String > responseEntityStr = restTemplate.
postForEntity(JsonObjectStudent, request, String.class);
JsonNode root = objectMapper.readTree(responseEntityStr.getBody());
assertNotNull(responseEntityStr.getBody());
assertNotNull(root.path("name").asText());
}
Usando @Test
@Test
public void postJsonObject()
throws IOException {
HttpEntity < String > request =
new HttpEntity < String > (studentJsonObject.toString(), headers);
String personResultAsJsonStr =
restTemplate.postForObject(createStudentUrl, request, String.class);
JsonNode root = objectMapper.readTree(personResultAsJsonStr);
assertNotNull(studentResultInJsonUrl);
assertNotNull(root);
assertNotNull(root.path("name").asText());
}
@Test
public void postJsonLocationObject()
throws JsonProcessingException {
HttpEntity < String > request = new HttpEntity <String> (studentJsonObject.toString(),
headers);
URI locationHeader = restTemplate.postForLocation(updateStudentUrl, request);
assertNotNull(locationHeader);
}
restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
list.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(list);
...
Payment payment= new Payment("Aa4bhs");
Payment res = restTemplate.postForObject("http://localhost:8080/aurest/rest/payment",
payment, Payment.class);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.put(url, entity);
RestTemplate restTemplate = new RestTemplate();
String url = "endpoint url";
String requestJson = "{\"queriedQuestion\":\"Is there pain in your hand?\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity < String > entity = new HttpEntity < String > (requestJson, headers);
String answer = restTemplate.postForObject(url, entity, String.class);
System.out.println(answer);
9. Ejemplo visto en https://howtodoinjava.com/spring-boot2/resttemplate/resttemplate-get-example/
Obtener todos los empleados
@GetMapping(value = "/employees",
produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public EmployeeListVO getAllEmployees(
@RequestHeader(name = "X-COM-PERSIST", required = true) String headerPersist,
@RequestHeader(name = "X-COM-LOCATION", defaultValue = "ASIA") String headerLocation)
{
LOGGER.info("Header X-COM-PERSIST :: " + headerPersist);
LOGGER.info("Header X-COM-LOCATION :: " + headerLocation);
EmployeeListVO employees = getEmployeeList();
return employees;
}
Consumiendo API
RestTemplate restTemplate = new RestTemplate();
final String baseUrl = "http://localhost:" + randomServerPort + "/employees";
URI uri = new URI(baseUrl);
ResponseEntity<String> result = restTemplate.getForEntity(uri, String.class);
//Verify request succeed
Assert.assertEquals(200, result.getStatusCodeValue());
Assert.assertEquals(true, result.getBody().contains("employeeList"));
Solicitud exitosa
RestTemplate restTemplate = new RestTemplate();
final String baseUrl = "http://localhost:"+randomServerPort+"/employees/";
URI uri = new URI(baseUrl);
HttpHeaders headers = new HttpHeaders();
headers.set("X-COM-PERSIST", "true");
headers.set("X-COM-LOCATION", "USA");
HttpEntity<Employee> requestEntity = new HttpEntity<>(null, headers);
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
//Verify request succeed
Assert.assertEquals(200, result.getStatusCodeValue());
Assert.assertEquals(true, result.getBody().contains("employeeList"));
Solicitud fallida
RestTemplate restTemplate = new RestTemplate();
final String baseUrl = "http://localhost:"+randomServerPort+"/employees/";
URI uri = new URI(baseUrl);
HttpHeaders headers = new HttpHeaders();
headers.set("X-COM-LOCATION", "USA");
HttpEntity<Employee> requestEntity = new HttpEntity<>(null, headers);
try
{
restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
Assert.fail();
}
catch(HttpClientErrorException ex)
{
//Verify bad request and missing header
Assert.assertEquals(400, ex.getRawStatusCode());
Assert.assertEquals(true, ex.getResponseBodyAsString().contains("Missing request header"));
}
Enlaces: