How to get live (spot) gold price 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 gold price using Java, we offer two sample code snippets using different method. Methods includes using OkHttp, and Unirest.

Instructions

  1. Get a free API to use by signing up at Metalpriceapi.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 gold price in Java

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

 

Using Unirest to fetch live gold price

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