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);
		
		
	}

}









No hay comentarios :

Publicar un comentario