Validar DNI desde java, Web de RENIEC a Escritorio

reniec peru web java
reniec peru web java

Buenas tardes, despues de tanto tiempo sin escribir, voy a mostrarles como le hice para pasar la consulta web de RENIEC, a un entorno de escritorio, para facilitarle las búsquedas a los usuarios y llevarlos a esto:

Bueno, vamos al código:

Archivo BusquedaCookie, encargado de obtener las cookies necesarias de la Session en la Web.

package conectarWeb;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;

/**
*
* @author CMOP
*/
public class BusquedaCookie {

public static final String USER_AGENT_FIREFOX = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)";
public static final String NOMBRE_COOKIE = "JSESSIONID";

public List<Object> buscarCookieLogueo(String urlseguridad) throws Exception {
List<Object> rpta = new ArrayList<Object>(1);
List<HttpCookie> cookies;
HttpsURLConnection connection = null;
try {
//Activar Oyente de Cookies
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
//-----------------------------------------------------------
//Asignar User Agent para evitar el filtro de navegador
System.setProperty("http.agent", USER_AGENT_FIREFOX);
//Crear un objeto URL
URL url = new URL(urlseguridad);
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(SSLByPass.getInstancia().getSslSocketFactory());
connection.setRequestMethod("POST");
connection.setDoInput(true);  // Esto permite leer el contenido despues de la peticion
connection.connect(); //Conectar
connection.getContent(); //Obtener contenido

//Leyendo la Cookie
CookieStore cookieJar = manager.getCookieStore();
cookies = cookieJar.getCookies();
// Leer la rpta
rpta.add(cookies);
StringBuilder answer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
reader.close();
connection.disconnect();
rpta.add(answer);
} catch (IOException e) {
if (connection.getResponseCode() != 500) {
} else {
System.out.println("No se puede obtener Cookies " + e);
}

throw e;
} catch (Exception e) {
System.out.println("No se puede obtener Cookies " + e);
throw e;
}
return rpta;
}
}

Archivo PeticionCookie, archivo encargado de hacer la consulta a la web del DNI

package conectarWeb;

import java.awt.Image;
import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpCookie;
import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
import java.util.List;

/**
*
* @author CMOP
*/
public class PeticionCookie {

public Image peticionConCookieImagen(String urlp, String metodo, String parametros, List<HttpCookie> cookies) throws Exception {
System.setProperty("http.agent", BusquedaCookie.USER_AGENT_FIREFOX);
try {
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
CookieStore cookieJar = manager.getCookieStore();
URL url = new URL(urlp);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(SSLByPass.getInstancia().getSslSocketFactory());
cookieJar.add(url.toURI(), cookies.get(0));
cookieJar.add(url.toURI(), cookies.get(1));

connection.setRequestMethod(metodo);
//-----------------------------------------------------------------------------------------
connection.connect(); //Conectar
connection.getContent();
BufferedInputStream reader = new BufferedInputStream(connection.getInputStream());
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
int c;
while ((c = reader.read()) != -1) {
byteArrayOut.write(c);
}
Image image = Toolkit.getDefaultToolkit().createImage(byteArrayOut.toByteArray());
reader.close();
return image;
} catch (Exception e) {
System.out.println("No se puede asignar la cookie " + e);
throw e;
}
}

public String peticionConCookieString(String urlp, String metodo, String parametros, List<HttpCookie> cookies) throws Exception {
System.setProperty("http.agent", BusquedaCookie.USER_AGENT_FIREFOX);
try {
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
CookieStore cookieJar = manager.getCookieStore();
URL url = new URL(urlp);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(SSLByPass.getInstancia().getSslSocketFactory());
cookieJar.add(url.toURI(), cookies.get(0));
cookieJar.add(url.toURI(), cookies.get(1));

connection.setRequestMethod(metodo);
connection.setDoOutput(true); // Esto permite agregar los parametros
// Escribiendo las variables
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(parametros);
writer.flush();
//-----------------------------------------------------------------------------------------
connection.connect(); //Conectar
connection.getContent();
StringBuilder answer = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
int linea = 1;
while ((line = reader.readLine()) != null) {
if (linea >= 154 && linea <= 156) {
answer.append(" ");
answer.append(line.trim());
}
//System.out.println(linea + " == " + line.trim());
linea++;
}
writer.close();
reader.close();
return answer.toString().replace("<br>", "");
} catch (Exception e) {
System.out.println("No se puede asignar la cookie " + e);
throw e;
}
}
}

Archivo Ventana, encargado de la visualizacion, y manejo de la GUI.

package validardni;

import conectarWeb.BusquedaCookie;
import conectarWeb.PeticionCookie;
import java.awt.Image;
import java.net.HttpCookie;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;

/**
*
* @author jestrada
*/
public class Ventana extends javax.swing.JDialog {

private List<Object> buscarCookieLogueo;

/** Creates new form Ventana */
public Ventana(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
this.setLocationRelativeTo(this);
}

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel1 = new javax.swing.JPanel();
lblImagen = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
lblRpta = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jTextField2 = new javax.swing.JTextField();
jTextField1 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("CONSULTAR NOMBRES");

lblImagen.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblImagen.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
lblImagen.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);

jLabel1.setText("DNI");

lblRpta.setBorder(javax.swing.BorderFactory.createEtchedBorder());

jButton1.setText("VALIDAR");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jButton1KeyPressed(evt);
}
});

jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});

jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(lblImagen, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)))
.addComponent(lblRpta, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblRpta, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(12, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jLabel2.setText("Consultando ...");
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
StringBuilder sb_parametros = new StringBuilder();
sb_parametros.append("accion=buscar&");
sb_parametros.append("tecla_7=6&");
sb_parametros.append("tecla_8=7&");
sb_parametros.append("tecla_9=9&");
sb_parametros.append("tecla_4=0&");
sb_parametros.append("tecla_5=1&");
sb_parametros.append("tecla_6=2&");
sb_parametros.append("tecla_1=3&");
sb_parametros.append("tecla_2=8&");
sb_parametros.append("tecla_3=4&");
sb_parametros.append("tecla_0=5&");
sb_parametros.append("nuDni=");
sb_parametros.append(jTextField1.getText().trim());
sb_parametros.append("&");
sb_parametros.append("imagen=");
sb_parametros.append(jTextField2.getText().trim());
sb_parametros.append("&");
sb_parametros.append("bot_consultar.x=13&");
sb_parametros.append("bot_consultar.y=24");
String parametros = sb_parametros.toString();
StringBuilder sb_url = new StringBuilder();
sb_url.append("https://cel.reniec.gob.pe/valreg/valreg.do;");
List<HttpCookie> cookies = (List<HttpCookie>) buscarCookieLogueo.get(0);
for (HttpCookie httpCookie : cookies) {
if (httpCookie.getName().compareToIgnoreCase("jsessionid") == 0) {
sb_url.append(httpCookie.getName());
sb_url.append("=");
sb_url.append(httpCookie.getValue());
}
}
try {
String buscarCookieLogueo1 = new PeticionCookie().peticionConCookieString(sb_url.toString(), "POST", parametros, (List<HttpCookie>) buscarCookieLogueo.get(0));
String s2 = new String(buscarCookieLogueo1.getBytes(),"ISO-8859-1");
lblRpta.setText(buscarCookieLogueo1);
jLabel2.setText("Consulta Terminada");
} catch (Exception ex) {
jLabel2.setText("Error al procesar Consulta");
ex.printStackTrace(System.out);
}
}
});
}

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField2.requestFocus();
}

private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
jButton1.requestFocus();
}

private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {
jButton1.doClick();
lblRpta.requestFocus();
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {
Ventana Principal = new Ventana(new javax.swing.JFrame(), true);
Principal.addWindowListener(new java.awt.event.WindowAdapter() {

@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
try {
Principal.buscarCookieLogueo = new BusquedaCookie().buscarCookieLogueo("https://cel.reniec.gob.pe/valreg/valreg.do");
Image buscarCookieLogueo1 = new PeticionCookie().peticionConCookieImagen("https://cel.reniec.gob.pe/valreg/codigo.do", "POST", "", (List<HttpCookie>) Principal.buscarCookieLogueo.get(0));
Principal.lblImagen.setIcon(new ImageIcon(buscarCookieLogueo1));

} catch (Exception ex) {
ex.printStackTrace();
}
Principal.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JLabel lblImagen;
private javax.swing.JLabel lblRpta;
// End of variables declaration
}
package conectarWeb;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
*
* @author Cmop
*/
public class SSLByPass {

private static SSLByPass instancia;
private SSLSocketFactory sslSocketFactory;

public SSLByPass() throws NoSuchAlgorithmException, KeyManagementException {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
}

@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
}

@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}};

// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
sslSocketFactory = sslContext.getSocketFactory();
}

public static SSLByPass getInstancia() throws NoSuchAlgorithmException, KeyManagementException {
if (instancia == null) {
instancia = new SSLByPass();
}
return instancia;
}

public SSLSocketFactory getSslSocketFactory() {
return sslSocketFactory;
}
}
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package conectarWeb;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
*
* @author Cmop
*/
public class SSLByPass {

private static SSLByPass instancia;
private SSLSocketFactory sslSocketFactory;

public SSLByPass() throws NoSuchAlgorithmException, KeyManagementException {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
}

@Override
public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
}

@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}};

// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
sslSocketFactory = sslContext.getSocketFactory();
}

public static SSLByPass getInstancia() throws NoSuchAlgorithmException, KeyManagementException {
if (instancia == null) {
instancia = new SSLByPass();
}
return instancia;
}

public SSLSocketFactory getSslSocketFactory() {
return sslSocketFactory;
}
}

Como siempre, subo el archivo jar, completamente funcional, para aquellos que deseen probarlo directamente:
ENLACE

31 comentarios sobre “Validar DNI desde java, Web de RENIEC a Escritorio

    1. Parece que se ha agregado alguna restricción, con el tema de los certificados, el cual no permite que el código funcione, lo arreglaré y colocaré el nuevo código fuente. saludos.

  1. Buen día amigo, he estado intentando probar su codigo pero hasta ahora no le logrado hacer que funcione, si me podria ayudar le estaría muy agradecido, al iniciar la aplicacion me salta un error “fatal alert”

  2. Excelente tu aporte

    java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    No se puede asignar la cookie java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

    la linia de error es esta
    Image buscarCookieLogueo1 = new PeticionCookie().peticionConCookieImagen(“https://cel.reniec.gob.pe/valreg/codigo.do”, “POST”, “”, (List) Principal.buscarCookieLogueo.get(0));

    No se si puedas hecharme una manito

  3. Muy bueno, gracias por el aporte, solo tienen que comentar la línea cookieJar.add(url.toURI(), cookies.get(1));… basta con el primer cookie… Saludos

  4. Cuando ejecuto en el netbeans me funciona bien, pero cuando lo genero a Jar y ejecuto el Jar no aparece el capcha.
    Pero al generar el jar me sale este Alerta en Netbeans
    Ventana.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.

  5. Alguien sabe si se logro a solucionar el problema de Received fatal alert: close_notify ??? Tiene años este aporte y no funciona.

Responder a Cmop Cancelar respuesta

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google photo

Estás comentando usando tu cuenta de Google. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s