Mostrando entradas con la etiqueta REST. Mostrar todas las entradas
Mostrando entradas con la etiqueta REST. Mostrar todas las entradas

viernes, 13 de mayo de 2022

Java REST client (2) :GET con autorización de "token"

 Ahora toca crar una petición con GET insertando el token en la cabecera (de tipo Authorisation), y atacando a una url diferente con distintos nombres de operacion.

Para simplficar suponemos que el token es "mitoken" y la url de servicio es:

https://urlserviciodeprueba/api/padron/motivospeticion 

sindo "motivosoperacion" el nombre de la operacion

Con  "curl" sería para una operación sin parámetros:


curl https://urlserviciodeprueba/api/padron/motivospeticion  -H "Authorization: Bearer mitoken"

y para una operacion con  parámetros

curl "https://urlserviciodeprueba/api/padron/volantefirmado?filtros[0].Nombre=CodigoProvincia&filtros[0].Valor=99&filtros[1].Nombre=CodigoMunicipio&filtros[1].Valor=999&filtros[2].Nombre=TipoDocumentoINE&filtros[2].Valor=1&filtros[3].Nombre=Documentacion&filtros[3].Valor=11111111H" -H "Authorization: Bearer mitoken"


Veamos todo el código en java tanto para el post anterior como este de forma unificada

hay que tener en cuenta de meter en gradle las dependencias de apache http client y Jackson (tambien puede falta algunas como lombok..)

//Apache
implementation 'org.apache.httpcomponents:httpclient:4.5.13'
    
/* Jackson */
implementation "com.fasterxml.jackson.core:jackson-core:2.13.2"
implementation "com.fasterxml.jackson.core:jackson-annotations:2.13.2"
implementation "com.fasterxml.jackson.core:jackson-databind:2.13.2.2"

Y el codigo java

package ph.utils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Getter;

public class HttpXimo {
	private CloseableHttpClient httpclient = null;
	@Getter private String urlAuth = null;
	@Getter private String urlService = null;

	public HttpEdu(String urlAuth, String urlService) {
		this.urlAuth = urlAuth;
		this.urlService = urlService;
		try {
			httpclient = HttpClients.createDefault();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String get(String url, String operation, String[] paramNames, String[] paramValues, String token) throws Exception {
		String urlWithParams=url+operation;
		for (int i=0; i<paramNames.length; i++) {
			String myUnionChar = "&";
			if (i==0) myUnionChar="?";
			urlWithParams+= myUnionChar + paramNames[i] + "=" + paramValues[i];
		}	
		System.out.println(urlWithParams);
		HttpGet request = new HttpGet(urlWithParams);
		//String auth = "Authorization: Bearer " + token;
		//byte[] encodedAuth = Base64.encodeBase64(
		//  auth.getBytes(StandardCharsets.ISO_8859_1));
		//String authHeader = "Basic " + new String(encodedAuth);
		String authHeader = "Bearer " + token;
		request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
		
		System.out.println("request.uri=" + request.getURI());
		for (Header header : request.getAllHeaders()) System.out.println("HEADER=" + header.getName() + "====" + header.getValue());

		//HttpClient client = HttpClientBuilder.create().build();
		HttpResponse response = httpclient.execute(request);
		HttpEntity entity = response.getEntity();
		InputStream in = entity.getContent();
		String s = new String(in.readAllBytes());
		System.out.println("ENTITY=" + s);
		// do something useful with the response body
		// and ensure it is fully consumed
		EntityUtils.consume(entity);
		return s;

	}
	
	public String post(String url, String[] paramNames, String[] paramValues) throws Exception {
		
		HttpPost httpPost = new HttpPost(this.urlAuth);
		List<NameValuePair> nvps = new ArrayList<>();

		//Add form parameters
		for (int i = 0; i < paramNames.length; i++)
			nvps.add(new BasicNameValuePair(paramNames[i], paramValues[i]));
		
		//Encode url
		httpPost.setEntity(new UrlEncodedFormEntity(nvps));
		
		//Get response
		CloseableHttpResponse response2 = httpclient.execute(httpPost);
		HttpEntity entity2 = response2.getEntity();
		
		//Read the response from input stream
		InputStream in = entity2.getContent();
		String s = new String(in.readAllBytes());
		
		//Close input stream
		EntityUtils.consume(entity2);
		return s;

	}
	
	public String getKeyValue(String jsonString, String key) throws JsonMappingException, JsonProcessingException {
		ObjectMapper  objMapper= new ObjectMapper();
		Map<String,String>mp=new HashMap<>();
		mp=objMapper.readValue(jsonString, mp.getClass());
		return mp.get(key);
	}	
	
	
	public static void main(String[] args) throws Exception {
		HttpEdu myHttp = new HttpXimo(
				"https://urlautorizaciondeprueba/identity/connect/token",
				"https://urlserviciodeprueba/api/padron/");
		String[] names = { "username", "password", "grant_type", "scope", "client_id", "client_secret" };
		String[] values = { "miUsuario", "miClave", "password", "miEmpresa",
				"yoMismo", "1234567890" };

		String strResponse= myHttp.post(myHttp.getUrlAuth(), names, values);
		System.out.println(strResponse);
		String token =myHttp.getKeyValue(strResponse, "access_token");
		System.out.println("TOKEN="+token);
		
		//===================MOTIVOS PETICION==============================
		String[] names1 = {};
		String[] values1 = {};
		
		strResponse= myHttp.get(myHttp.getUrlService(), "motivospeticion", names1, values1, token);
		System.out.println(strResponse);
		
		//===================VOLANTE FIRMNADO==============================
		String[] names2 = { "filtros[0].Nombre", "filtros[0].Valor", "filtros[1].Nombre", "filtros[1].Valor", 
				"filtros[2].Nombre", "filtros[2].Valor","filtros[3].Nombre", "filtros[3].Valor" };
		String[] values2 = { "CodigoProvincia", "99", "CodigoMunicipio", "999",
				"TipoDocumentoINE", "1", "Documentacion", "11111111H"  };
				
		strResponse= myHttp.get(myHttp.getUrlService(), "volantefirmado", names2, values2, token);
		System.out.println(strResponse);
		
		
	}

}









Java REST client (I) :Post con parametros de formulario

 1. Introducción

Tengo que conseguir un "token" que me servira para consumir la REST api para un aplicación que estoy intentando integrar con otra.

Para ello me suministran:

1. la URL a la cual llamar (por ejemplo ficticiamente: 

 https://empresaauthorization.es/identity/connect/token

2. Usuario y contraseña como parámetros:

Parametro:  "username" valor: "miUsuario"

Parametro: "password"  valor: "miClave"

3. Otros parametros adicionales

Parametro:  "grant_type" valor: "password"

Parametro: "scope"  valor: "miAplicacion"

Parametro: "client_id"  valor: "yoMismo"

Parametro: "client_secret"  valor: "AH0124EF5832HA321"



2. Llamadas

Con "curl" se haría así:

curl -X POST --data "username=miUsuario&password=miClave&grant_type=password&scope=miAplicacion&client_id=yoMismo&client_secret=AH0124EF5832HA321" -k https://empresaauthorization.es/identity/connect/token

En cambio en Java he creado este módulo que me ha hecho penar:

En gradle le he dado esta dependencia

implementation 'org.apache.httpcomponents:httpclient:4.5.13'

package ph.utils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

public class HttpXimo {
	private CloseableHttpClient httpclient = null;
	private String url = null;

	public HttpEdu(String url) {
		this.url = url;
		try {
			httpclient = HttpClients.createDefault();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String post(String[] paramNames, String[] paramValues) throws Exception {
		
		HttpPost httpPost = new HttpPost(this.url);
		List<NameValuePair> nvps = new ArrayList<>();

		//Add form parameters
		for (int i = 0; i < paramNames.length; i++)
			nvps.add(new BasicNameValuePair(paramNames[i], paramValues[i]));
		
		//Encode url
		httpPost.setEntity(new UrlEncodedFormEntity(nvps));
		
		//Get response
		CloseableHttpResponse response2 = httpclient.execute(httpPost);
		HttpEntity entity2 = response2.getEntity();
		
		//Read the response from input stream
		InputStream in = entity2.getContent();
		String s = new String(in.readAllBytes());
		
		//Close input stream
		EntityUtils.consume(entity2);
		return s;

	}

        public static void main(String[] args) throws Exception {
		HttpXimo myHttp = new HttpEdu("https://empresaauthorization.es/identity/connect/token");
		String[] names = { "username", "password", "grant_type", "scope", "client_id", "client_secret" };
		String[] values = { "Parametro", "miClave", "password", "miAplicacion",
				"yoMismo", "AH0124EF5832HA321" };

		System.out.println("HOLA=" + myHttp.post(names, values));
	}

	

Y la respuesta que obtenemos es esta (en formato JSON)

{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IjF6ZTUxZnlxcFFZVkJVaTJlMzVTRmVxX0J0byIsImtpZCI6IjF6ZTUxZnlxcFFZVkJVaTJlMzVTRmVxX0J0byJ9.eyJjbGllbnRfaWQiOiJJbnRlcnB1YmxpY2EiLCJzY29wZSI6IkludGVycHVibGljYSIsInN1YiI6IjMzOTBlYjAyLTRiM2ItNDVmMy1iMzk3LWEzMDhmOWQ2YTNlNCIsImFbciI6WyJwYXNzd29yZCJdLCJhdvRoX3RpbWUiOjE2NTI0MjIxMjgsImlkcCI6Imlkc3J2IiwicHJlZmVycmVkX3VzZXJuYW1lIjoiVGF2ZXJuZXNWYWxsZGlnbmFTZWRpIiwiZW1haWwiOiJub0Buby5jb20iLCJlbWFpbF92ZXJpZmllZCI6InRydWUiLCJwaG9uZV9udW1iZXIiOiIxMjM0NTY3ODkiLCJwaG9uZV9udW1iZXJfdmVyaWZpZWQiOiJ0cnVlIiwiVXN1YXJpbyI6IjM0MyIsIlNlcnZpZG9yIjoiMiIsIkRvbWluaW8iOiI0IiwiRW50aWRhZCI6IjM0MyIsInJvbGUiOlsiRG9tYWluIiwiSW50ZXJwdWJsaWNhIiwiUGFkcm9uIl0sImp0aSI6ImQxNzNiZTY5ZGRjOWUxMDYyNDkzZjZlYzNiMDgxMWIzIiwiaXNzIjoiaHR0cHM6Ly9pbnRlcnB1YmxpY2FhdXRob3JpemF0aW9uLmRpdmFsLmVzL2lkZW50aXR5IiwiYXVkIjoiaHR0cHM6Ly9pbnRlcnB1YmxpY2FhdXRob3JpemF0aW9uLmRpdmFsLmVzL2lkZW50aXR5L3Jlc291cmNlcyIsImV4cCI6MTY1MjQyNTcyOCwibmJmIjoxNjUyNDIyMTI4fQ.ewb85x5PDL6gGvhdeZUlhn15DfGfZ4TgeTB7nY5RvAmUF0tFUs-gG38cZ5LcF87yVALlPzB8gwKMbVHfXVseO2cXpiQTxlF4xLF006aDXT1zN9bTIcFb55BUyDFeJmQyzW_euUi8KX0kKDK3XCkS01LvK_7NGIGeL_M78m7_4LumqnurWUAv2JEApIBZkBFXZ_zREk1LzJt1Pqlt6muTcS8XEZsLXK8EoTNjWkkHZzU0VdXArwSy-RKQRm3HbOr43eV96eMAKudoY8nbAeeqzsS5_qLk7soNUihwlvoM9A-EdjDsySFf_KxTtWAyemkdoE5PRPTAwmXoYPBuwKOwdw","expires_in":3600,"token_type":"Bearer"}

Para leer la respuesta se añade este código sustituyendo al método "main"


        public String getKeyValue(String jsonString, String key) throws JsonMappingException, JsonProcessingException {
		ObjectMapper  objMapper= new ObjectMapper();
		Map<String,String>mp=new HashMap<>();
		mp=objMapper.readValue(jsonString, mp.getClass());
		return mp.get(key);
	}	
	
	
	public static void main(String[] args) throws Exception {
		HttpXimo myHttp = new HttpEdu("https://interpublicaauthorization.dival.es/identity/connect/token");
		String[] names = { "username", "password", "grant_type", "scope", "client_id", "client_secret" };
		String[] values = { "Parametro", "miClave", "password", "miAplicacion",
				"yoMismo", "AH0124EF5832HA321" };
String strResponse= myHttp.post(names, values); System.out.println(strResponse); String token =myHttp.getKeyValue(strResponse, "access_token"); System.out.println(token); }

Ahora ya tenemos el token, vamos a por la segunda parte que consiste en utilizar este token para usar la REST API