Simple Currency Conversion using Google Calculator and Java


Here’s a little trick that I use to generate seed values for some of our mock components to ensure these values are fairly realistic.

Google has a web service that when queried returns a JSON string for calculated values. It’s basically a web service for the extremely useful Google Calculator.

If you point your browser to http://www.google.com/ig/calculator?hl=en&q=1GBP%3D%3FAUD you can see the result for yourself. I’ve wrapped this service in a small java class to demonstrate how to perform these types of calculations programmatically. The class makes use of GSON, which is another really useful Google API for converting JSON objects into POJOs.

package com.caplin.datasrc.ret.ct;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;

import com.google.gson.Gson;

public class SeedGenerator
{
	static class Result
    {
        private String lhs;
        private String rhs;

        public String getLhs()
        {
        	return lhs;
        }

        public String getRhs()
        {
        	return rhs;
        }

        public void setLhs(String lhs)
        {
        	this.lhs = lhs;
        }

        public void setRhs(String rhs)
        {
        	this.rhs = rhs;
        }
    }

	public static void main(String[] args) throws Exception
	{
	    String google = "http://www.google.com/ig/calculator?hl=en&q=";
	    String baseCurrency = "GBP";
	    String termCurrency = "AUD";
	    String charset = "UTF-8";

	    URL url = new URL(google + baseCurrency + "%3D%3F" + termCurrency);

	    Reader reader = new InputStreamReader(url.openStream(), charset);
	    Result result = new Gson().fromJson(reader, Result.class);

	    // Get the value without the term currency.
	    String amount = result.getRhs().split("\\s+")[0];

	    System.out.println(amount);
	}
}

The beauty of Google Calculator is of course that it can be used for any conversion. If you point your browser to http://www.google.com/ig/calculator?hl=en&q=1%20mile=?kilometer you will get the following result:

{lhs: "1 mile",rhs: "1.609344 kilometers",error: "",icc: false}

Even extremely arbitrary calculations work! For example http://www.google.com/ig/calculator?hl=en&q=furlongs%20in%20light%20year produces:

{lhs: "1 light year",rhs: "4.70279985 \x26#215; 10\x3csup\x3e13\x3c/sup\x3e furlongs",error: "",icc: false}

which looks like 4.70279985 × 1013. Pretty cool!

Related Posts with Thumbnails

12 Comments

  • ravi says:

    Nice one .. It is very helpful for me
    Thanks
    :)

  • someguy says:

    sounds about right – 1 light year is about 4000 furlongs….maybe not

  • Rasika says:

    Thanx really helpful.
    As i did experiments hope the url should be in this format
    “http://www.google.com/ig/calculator?hl=en&q=1GBP=?USD”
    isn’t that your code doesn’t add the initial amount to the url ? hope it have to be there just after “q=”.

  • ali says:

    thanks for sharing

    run:
    Exception in thread “main” java.io.IOException: Server returned HTTP response code: 400 for URL: http://www.google.com/ig/calculator?hl=en&q=GBP%3D%3FUSD
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
    at java.net.URL.openStream(URL.java:1010)
    at com.caplin.datasrc.ret.ct.SeedGenerator.main(SeedGenerator.java:52)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 3 seconds)

    how to fix this ?

    —–

  • ali says:

    Sorry, about my first post :
    i missed to say that when i run your program: in my netbeans developer
    i get the following lines:
    run:
    Exception in thread “main” java.io.IOException: Server returned HTTP response code: 400 for URL: http://www.google.com/ig/calculator?hl=en&q=GBP%3D%3FUSD
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
    at java.net.URL.openStream(URL.java:1010)
    at com.caplin.datasrc.ret.ct.SeedGenerator.main(SeedGenerator.java:52)
    Java Result: 1
    BUILD SUCCESSFUL (total time: 3 seconds)

    how to fix this ?

  • Pattabhi says:

    new Gson().fromJson(reader, Result.class)

    the above statement returned null, why pls help me

    Exception in thread “main” java.lang.NullPointerException
    at com.mm.CurrencyConverter.main(CurrencyConverter.java:42)

  • The one thing about Chicago auto insurance that’s specific to Chicago yet fails to be special. A broker is a go-between that helps link a motorist or customer with an insurance provider and protection plan. Visit for money saving tips and more information on obtaining cheap affordable car insurance quotes from the most reputable insurance carriers in the industry. If you drive a newer model vehicle, be sure to review the policy details closely to see how the company handles repairs in the case of a claim.

  • Beatriz says:

    It is in point of fact a great and useful piece of information. I am happy that you
    simply shared this useful information with us. Please
    stay us up to date like this. Thanks for sharing.

  • Rao Qasim says:

    hi
    i need api that create a table and update currency rates on daily bases in that table from which i will able to fetch required currency rate any time. currently i am using api that converts currency at real time and it is working fine but i need updated currency rates on daily bases in db table.

    thnx,

  • Online courses simply provide students a convenient way to learn all of
    these subjects through correspondence and at the student’s pace.

    All the details related to our business are highly important
    and confidential and we should be sure of keeping it safe. Open – Pro
    was established to provide ERP functionality to small and medium-sized business [SMBs], whose need for
    affordable and less complex business software has not been met by traditional ERP vendors.

Leave a Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image