Welcome to the UnirateAPI Java documentation! Our free exchange rate API provides real-time currency conversion capabilities that you can easily integrate into your Java applications. Whether you're building a Spring application, Android app, or any Java system that needs currency conversion, our API has you covered.
UnirateAPI is designed to be developer-friendly and reliable, with a focus on simplicity and performance. This guide will show you how to make API requests using Java's standard libraries.
For more detailed information about our API endpoints, rate limits, and advanced features, please check our main API documentation.
Below you'll find examples showing how to use our API with Java using different approaches.
You can use our API in Java by making HTTP requests using either the classic HttpURLConnection (Java 8+) or the modern HttpClient (Java 11+). We'll show you both approaches below.
// Option 1: Using Java's HttpURLConnection (Compatible with Java 8+)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.HashMap;
import org.json.JSONObject;
public class CurrencyConverter {
private static final String BASE_URL = "https://api.unirateapi.com/api";
private final String apiKey;
public CurrencyConverter(String apiKey) {
this.apiKey = apiKey;
}
public JSONObject convert(String fromCurrency, String toCurrency, double amount) throws Exception {
Map params = new HashMap<>();
params.put("api_key", apiKey);
params.put("from", fromCurrency);
params.put("to", toCurrency);
params.put("amount", String.valueOf(amount));
String response = sendGetRequest("/convert", params);
return new JSONObject(response);
}
public double getRate(String fromCurrency, String toCurrency) throws Exception {
Map params = new HashMap<>();
params.put("api_key", apiKey);
params.put("base", fromCurrency);
params.put("symbols", toCurrency);
String response = sendGetRequest("/rates", params);
JSONObject jsonResponse = new JSONObject(response);
return jsonResponse.getJSONObject("rates").getDouble(toCurrency);
}
public JSONObject getCurrencies() throws Exception {
Map params = new HashMap<>();
params.put("api_key", apiKey);
String response = sendGetRequest("/currencies", params);
return new JSONObject(response);
}
private String sendGetRequest(String endpoint, Map params) throws Exception {
StringBuilder urlBuilder = new StringBuilder(BASE_URL + endpoint + "?");
for (Map.Entry entry : params.entrySet()) {
urlBuilder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString()));
urlBuilder.append("=");
urlBuilder.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString()));
urlBuilder.append("&");
}
// Remove the last "&"
String urlString = urlBuilder.toString();
urlString = urlString.substring(0, urlString.length() - 1);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
} else {
throw new RuntimeException("API request failed with response code: " + responseCode);
}
}
public static void main(String[] args) {
try {
String apiKey = "YOUR_API_KEY";
CurrencyConverter converter = new CurrencyConverter(apiKey);
// Convert 100 USD to EUR
JSONObject result = converter.convert("USD", "EUR", 100);
System.out.println("Converted amount: " + result.getDouble("result") + " " + result.getString("to"));
// Get exchange rate from USD to EUR
double rate = converter.getRate("USD", "EUR");
System.out.println("1 USD = " + rate + " EUR");
// Get supported currencies
JSONObject currencies = converter.getCurrencies();
System.out.println("Supported currencies: " + currencies.keySet().toString());
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
// Option 2: Using Java's modern HttpClient (Java 11+)
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class UnirateApiClient {
private static final String BASE_URL = "https://api.unirateapi.com/api";
private final String apiKey;
private final HttpClient httpClient;
public UnirateApiClient(String apiKey) {
this.apiKey = apiKey;
this.httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.build();
}
public String convert(String fromCurrency, String toCurrency, double amount) throws Exception {
Map params = new HashMap<>();
params.put("api_key", apiKey);
params.put("from", fromCurrency);
params.put("to", toCurrency);
params.put("amount", String.valueOf(amount));
return sendGetRequest("/convert", params);
}
public String getRate(String fromCurrency, String toCurrency) throws Exception {
Map params = new HashMap<>();
params.put("api_key", apiKey);
params.put("base", fromCurrency);
params.put("symbols", toCurrency);
return sendGetRequest("/rates", params);
}
private String sendGetRequest(String endpoint, Map params) throws Exception {
String queryString = params.entrySet().stream()
.map(entry -> URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8) + "=" +
URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
String urlString = BASE_URL + endpoint + "?" + queryString;
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create(urlString))
.build();
HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return response.body();
} else {
throw new RuntimeException("API request failed with status code: " + response.statusCode());
}
}
// Usage with modern Jackson JSON parsing (requires jackson-databind dependency)
public static void main(String[] args) {
try {
String apiKey = "YOUR_API_KEY";
UnirateApiClient client = new UnirateApiClient(apiKey);
// Convert 100 USD to EUR
String conversionResult = client.convert("USD", "EUR", 100);
System.out.println("Conversion result: " + conversionResult);
// Get the exchange rate between USD and EUR
String rateResult = client.getRate("USD", "EUR");
System.out.println("Rate result: " + rateResult);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
// API Response:
{
"from": "USD",
"to": "EUR",
"amount": 100,
"result": 92.45
}
// Console Output:
Converted amount: 92.45 EUR
1 USD = 0.9245 EUR
Supported currencies: [USD, EUR, GBP, JPY, AUD, ...]
Sign up now to get your API key and start converting currencies in your java applications.
Get Your API Key