使用java转换货币

时间:2015-10-11 10:50:24

标签: java gson

我需要在设定的货币之间进行转换。 我找到了一个简单的教程:http://blog.caplin.com/2011/01/06/simple-currency-conversion-using-google-calculator-and-java/

这是我的代码:(我顺便导入gson库)

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

}

我收到了错误:

 Exception in thread "main" java.io.FileNotFoundException: http://www.google.com/ig/calculator?hl=en&q=GBP%3D%3FAUD
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at SeedGenerator.main(SeedGenerator.java:45)

有人可以解释一下我做错了什么。我认为这可能是实际URL的问题。我可能使用了错误的吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

这是使用correct URL的正确String结构:

"https://www.google.com/finance/converter?a=" 
+ toConvert + "&from=" 
+ firstCurrency + "&to" 
+ secondCurrency;