real-time currency exchange from MXN to USD online store to show prices


I have an online store and the prices of each product are shown in dollars and one side will show an "approx" in Mexican pesos as what aliexpress does, or failing to know if to handle these currency changes depending of the language that is selected, I have to make the change manually, if it is from mexico the person shows the prices in pesos MXN and so respectively for now MXN and USD are the 2 currencies that I will negotiate, rather as the currency exchange does those pages like amazon and aliexpress, we must bear in mind that the price of the dollar changes constantly and the Mexican price must be updated. I am developing in spring MVC, and angular js, and a little Servlets

asked by jonathan 25.07.2016 в 08:21

1 answer


The Bank of Mexico published a WebService with the daily price of the Mexican peso in:


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.




import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Banxico{

    //Variables del webservice
    private final String URL        = "";
    private final String NS         = "";
    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=\"\" xmlns:apachesoap=\"\" "
        + "xmlns:impl=\"" + NS + "\" xmlns:intf=\"" + NS + "\" xmlns:soapenc=\"\" "
        + "xmlns:wsdl=\"\" xmlns:wsdlsoap=\"\" "
        + "xmlns:xsd=\"\" xmlns:xsi=\"\" >"
        + "<SOAP-ENV:Body><mns:" + OPERATION + " xmlns:mns=\"" + NS + "\" SOAP-ENV:encodingStyle=\"\">"
        + "</mns:" + OPERATION + "></SOAP-ENV:Body></SOAP-ENV:Envelope>";
    private final static String REGEX = 
        + "\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();



    // HTTP POST
    private String sendPost() throws Exception {

        URL obj = new URL(URL);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // Configuracion del Header
        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
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());

        // 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) {

        // 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: " +"cotizacion"));
            System.out.println("Fecha: " +"fecha"));
            System.out.println("Descripcion: " +"titulo"));
        } else {

    // Funcion para decodificar las 5 entities mas comunes
    private static String unescapeCommonEntities( final String xmle )
        return xmle.replaceAll( "&lt;", "<" )
                    .replaceAll( "&gt;", ">" )
                    .replaceAll( "&amp;", "&" )
                    .replaceAll( "&apos;", "'" )
                    .replaceAll( "&quot;", "\"" );



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


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.

answered by 25.07.2016 в 23:43