How to get live (spot) forex rate using API in Java?

< Back to Guides

Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. To get live forex rate using Java, we offer two sample code snippets using different method. Methods includes using OkHttp, and Unirest.

Instructions

  1. Get a free API key to use by signing up at forexrateapi.com and replace REPLACE_ME with your API key.
  2. Update base value to a currency or remove this query param.
  3. Update currencies value to a list of values or remove this query param.

For 2 and 3, you can find this documented at Offical Documentation

 

Using OkHttp to fetch live forex rate in Java

OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
Request request = new Request.Builder()
  .url("https://api.forexrateapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=EUR,JPY,CAD")
  .method("GET", null)
  .build();
Response response = client.newCall(request).execute();

 

Using Unirest to fetch live forex rate

Unirest.setTimeouts(0, 0);
HttpResponse<String> response = Unirest.get("https://api.forexrateapi.com/v1/latest?api_key=REPLACE_ME&base=USD&currencies=EUR,JPY,CAD")
  .asString();