Java Example for Calling API
Java Example for Calling the CatFee.IO REST API
Prerequisites
Use Java 11 or later. The example uses only Java standard-library classes:
java.net.http.HttpClient
javax.crypto.Mac
javax.crypto.spec.SecretKeySpecExample Code
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
public class CatFeeAPIExample {
private static final String API_KEY = "your_api_key"; // Replace with your API Key
private static final String API_SECRET = "your_api_secret"; // Replace with your API Secret
private static final String BASE_URL = "https://api.catfee.io";
public static void main(String[] args) throws Exception {
// HTTP method
String method = "POST"; // Change to "GET", "PUT", or "DELETE" as needed
// Example: Create a buy energy order
String path = "/v1/order";
String clientOrderId = UUID.randomUUID().toString();
Map<String, String> queryParams = new LinkedHashMap<>();
queryParams.put("quantity", "65000");
queryParams.put("receiver", "TRON_ADDRESS");
queryParams.put("duration", "1h");
queryParams.put("client_order_id", clientOrderId);
queryParams.put("activate", "true");
// Generate headers
String timestamp = generateTimestamp();
String requestPath = buildRequestPath(path, queryParams);
String signature = generateSignature(timestamp, method, requestPath);
// Create HTTP request
String url = BASE_URL + requestPath;
HttpRequest request = createRequest(url, method, timestamp, signature);
// Send the request and get the response
System.out.println("Client Order ID: " + clientOrderId);
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Print response
System.out.println("Response Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
// Handle potential error messages
if (response.statusCode() < 200 || response.statusCode() >= 300) {
System.out.println("HTTP request failed: " + response.body());
}
}
// Generate current UTC timestamp in ISO 8601 format
public static String generateTimestamp() {
return Instant.now().toString();
}
// Build request path with query parameters
public static String buildRequestPath(String path, Map<String, String> queryParams) {
if (queryParams == null || queryParams.isEmpty()) {
return path;
}
String queryString = queryParams.entrySet().stream()
.map(entry -> URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8)
+ "="
+ URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&", "?", ""));
return path + queryString;
}
// Generate signature
public static String generateSignature(String timestamp, String method, String requestPath) throws Exception {
String signString = timestamp + method.toUpperCase() + requestPath;
return hmacSHA256(signString, API_SECRET);
}
// HMAC-SHA256 signature generation
public static String hmacSHA256(String data, String secret) throws Exception {
Mac sha256Hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256Hmac.init(secretKey);
byte[] hash = sha256Hmac.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(hash);
}
// Create HTTP request supporting GET, POST, PUT, DELETE
public static HttpRequest createRequest(String url, String method, String timestamp, String signature) {
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
.uri(URI.create(url))
.timeout(Duration.ofSeconds(15))
.header("Content-Type", "application/json")
.header("CF-ACCESS-KEY", API_KEY)
.header("CF-ACCESS-SIGN", signature)
.header("CF-ACCESS-TIMESTAMP", timestamp);
switch (method.toUpperCase()) {
case "POST":
requestBuilder.POST(HttpRequest.BodyPublishers.noBody());
break;
case "PUT":
requestBuilder.PUT(HttpRequest.BodyPublishers.noBody());
break;
case "DELETE":
requestBuilder.DELETE();
break;
case "GET":
requestBuilder.GET();
break;
default:
throw new UnsupportedOperationException("Unsupported HTTP method: " + method);
}
return requestBuilder.build();
}
}Code Explanation
methodVariable: Themethodin themain()function is defined as"POST", which can be changed to"GET","PUT", or"DELETE"as needed.Generate Current Timestamp: The
generateTimestamp()function returns the current UTC time in ISO 8601 format usingInstant.now().toString().Build Request Path: The
buildRequestPath()function takes query parameters and appends them to the path to form the full request path.Generate Signature: The
generateSignature()function creates the string to be signed by concatenatingtimestamp + method + requestPath, and uses thehmacSHA256()method with the API Secret to generate the signature.HMAC-SHA256 Signing: The
hmacSHA256()function implements HMAC-SHA256 signing and returns a Base64-encoded result.Create Request: The
createRequest()function dynamically builds the HTTP request based on the specified method (GET, POST, PUT, DELETE). For POST and PUT requests, it usesHttpRequest.BodyPublishers.noBody().Send Request and Handle Response: It uses
HttpClientto send the HTTP request and prints the response status and body. If the response status is not 200, it logs an error.
Notes
API Key & Secret: Make sure to replace
API_KEYandAPI_SECRETwith the actual values obtained from CatFee.IO.Purpose of the Signature: The signature ensures the integrity and authenticity of the request. It is generated using the combination of timestamp, HTTP method, request path, and query parameters.
Signed Request Path: The encoded query string and parameter order must be identical in the signature and actual URL.
LinkedHashMappreserves the insertion order used by this example.Idempotent Retries: Use a unique
client_order_idof no more than 64 characters for each new order, and reuse it after a timeout or connection failure.HTTP Methods: The sample supports POST, PUT, GET, and DELETE methods. All parameters are passed through the URL query string.
Handling Response: HTTP
200does not necessarily mean business success. Parse the JSON response with your application's JSON library and verify thatcodeis0.
Summary
This example demonstrates how to securely interact with CatFee.IO Rest API in Java. By using HMAC-SHA256 signatures and proper query handling, it ensures each request is valid and protected. You can customize this code to perform different operations and HTTP methods as needed.
For any questions or further assistance, feel free to contact the CatFee.IO support team.
Last updated