The Bank of Mexico published a WebService with the daily price of the Mexican peso in:
link
This WebService can be consumed directly from Java. This is a simple example of how it can be used.
But I have to make some reservations. To simplify the example, I personally preferred to make a request directly by HTTP POST so as not to fall into dependencies that not everyone can use. Also, on the XML returned, I am getting the values from the raw string with a RegEx (without using a parser for the XML, knowing that it could be broken if the structure of the response changes). And I'm not capturing possible errors either ... As you can see, there's a lot to improve in this code. I leave it as a pending task.
Code:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Banxico{
//Variables del webservice http://www.banxico.org.mx/DgieWSWeb/DgieWS?WSDL
private final String URL = "http://www.banxico.org.mx/DgieWSWeb/DgieWS";
private final String NS = "http://ws.dgie.banxico.org.mx";
private final String OPERATION = "tiposDeCambioBanxico";
private final String CHARSET = "ISO-8859-1";
private final String ENVELOPE = "<?xml version=\"1.0\" encoding=\"" + CHARSET + "\" standalone=\"no\"?>"
+ "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:apachesoap=\"http://xml.apache.org/xml-soap\" "
+ "xmlns:impl=\"" + NS + "\" xmlns:intf=\"" + NS + "\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" "
+ "xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:wsdlsoap=\"http://schemas.xmlsoap.org/wsdl/soap/\" "
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" >"
+ "<SOAP-ENV:Body><mns:" + OPERATION + " xmlns:mns=\"" + NS + "\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
+ "</mns:" + OPERATION + "></SOAP-ENV:Body></SOAP-ENV:Envelope>";
private final static String REGEX =
"<bm:Series\s++TITULO\s*+=\s*+\"(?<titulo>[^\"]*+)\""
+ "\s++IDSERIE\s*+=\s*+\"SF43718\"[^>]*+>"
+ "\s*+<bm:Obs\s++TIME_PERIOD\s*+=\s*+\"(?<fecha>[^\"]*+)\""
+ "\s++OBS_VALUE\s*+=\s*+\"(?<cotizacion>[^\"]*)";
public static void main(String[] args) throws Exception {
Banxico http = new Banxico();
String resultado = http.sendPost();
procesarTexto(resultado);
}
// HTTP POST
private String sendPost() throws Exception {
URL obj = new URL(URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Configuracion del Header
con.setRequestMethod("POST");
con.setRequestProperty("Accept-Encoding", "gzip, deflate");
con.setRequestProperty("Content-Encoding", "deflate");
con.setRequestProperty("Content-Type", "text/xml; charset=" + CHARSET);
con.setRequestProperty("SOAPAction", OPERATION);
// Enviar el request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(ENVELOPE);
wr.flush();
wr.close();
// Leer la respuesta
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Devolver el XML
return response.toString();
}
// Imprimir los datos
private static void procesarTexto(final String uxml) {
// Sacar las entities
// (se rompe el XML pero es mas facil procesarlo directamente)
String xml = unescapeCommonEntities(uxml);
// Obtener los campos buscados con una expresion regular sobre todo el xml
Pattern idPatt = Pattern.compile(REGEX);
Matcher m = idPatt.matcher(xml);
if (m.find()) {
System.out.println("Cotizacion: " + m.group("cotizacion"));
System.out.println("Fecha: " + m.group("fecha"));
System.out.println("Descripcion: " + m.group("titulo"));
} else {
System.out.println("ERROR!");
}
}
// Funcion para decodificar las 5 entities mas comunes
private static String unescapeCommonEntities( final String xmle )
{
return xmle.replaceAll( "<", "<" )
.replaceAll( ">", ">" )
.replaceAll( "&", "&" )
.replaceAll( "'", "'" )
.replaceAll( """, "\"" );
}
}
Exit
Cotizacion: 18.7569
Fecha: 2016-07-25
Descripcion: Tipo de cambio Pesos por dólar E.U.A. Tipo de cambio para solventar obligaciones denominadas en moneda extranjera Fecha de determinación (FIX)
Online Demo
Demo at tutorialspoint.com
Disclaimer
The truth is, I am completely unaware of the conditions of use of the webservice, nor how reliable it is. Before using it in production, I strongly recommend to see the conditions of the Bank and even contact them to consult. If this code or part of it is used, it is your responsibility.