Consumir Servicio Spring Boot + JWT con 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 );
}};
}
}
Comentarios
Publicar un comentario