# Java Guide for Calling Mefree.NET API

This guide explains how to use **Java** to interact with the Mefree.NET API. It covers signature generation, HTTP request construction, and example API calls.

***

#### **1. Overview of the Signature Rules**

**1.1 Signature String Rules**

Mefree.NET API requires a signature mechanism for authentication. Ensure the signature is generated following these rules:

1. **Construct the String to Sign**:

   ```
   sign = timestamp + method + requestPath
   ```

   * **timestamp**: UTC time in ISO 8601 format, e.g., `2024-11-26T12:34:56.789Z`.
   * **method**: HTTP method, e.g., `GET` or `POST`.
   * **requestPath**: API request path (including query parameters), such as:
     * `/api/config`
     * `/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1`
2. **Generate the Signature**:
   * Use the **HMAC-SHA256** algorithm with the **Secret Key** to hash the string.
   * Encode the resulting hash with **Base64** to obtain the final signature.

***

**1.2 Required HTTP Headers**

Each request must include the following headers:

* `Content-Type: application/json`
* `MF-ACCESS-KEY`: Your API Key.
* `MF-ACCESS-SIGN`: The generated signature.
* `MF-ACCESS-TIMESTAMP`: Current UTC timestamp.

***

#### **2. Environment Setup**

Ensure you have the following dependencies available in your Java environment:

* **Java Standard Libraries** for time handling, Base64 encoding, and HTTP requests.
* If using external libraries, you can include:
  * `Apache HttpClient` for HTTP requests.
  * `org.apache.commons.codec` for HMAC-SHA256 and Base64 encoding.

***

#### **3. Signature Generation Method**

Below is the Java implementation for generating the signature:

```java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class MefreeApiHelper {

    // Generate HMAC-SHA256 signature
    public static String generateSignature(String timestamp, String method, String requestPath, String secretKey) {
        try {
            String message = timestamp + method + requestPath;
            Mac mac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
            mac.init(secretKeySpec);
            byte[] hash = mac.doFinal(message.getBytes());
            return Base64.getEncoder().encodeToString(hash);
        } catch (Exception e) {
            throw new RuntimeException("Error while generating signature: " + e.getMessage());
        }
    }

    // Get current UTC timestamp in ISO 8601 format
    public static String getUtcTimestamp() {
        return java.time.ZonedDateTime.now(java.time.ZoneOffset.UTC)
                .format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
    }
}
```

***

#### **4. HTTP Request Helper**

The following code demonstrates how to make HTTP requests with the required headers:

```java
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class MefreeApiClient {
    private static final String BASE_URL = "https://api.mefree.net";
    private static final String API_KEY = "your_api_key";      // Replace with your API Key
    private static final String SECRET_KEY = "your_secret_key"; // Replace with your Secret Key

    public static String sendRequest(String method, String requestPath) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            String timestamp = MefreeApiHelper.getUtcTimestamp();
            String signature = MefreeApiHelper.generateSignature(timestamp, method, requestPath, SECRET_KEY);

            // Create HTTP request
            HttpRequestBase request;
            if (method.equalsIgnoreCase("GET")) {
                request = new HttpGet(BASE_URL + requestPath);
            } else if (method.equalsIgnoreCase("POST")) {
                request = new HttpPost(BASE_URL + requestPath);
            } else {
                throw new IllegalArgumentException("Unsupported HTTP method: " + method);
            }

            // Add headers
            request.setHeader("Content-Type", "application/json");
            request.setHeader("MF-ACCESS-KEY", API_KEY);
            request.setHeader("MF-ACCESS-SIGN", signature);
            request.setHeader("MF-ACCESS-TIMESTAMP", timestamp);

            // Send the request
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                String responseBody = EntityUtils.toString(response.getEntity());

                if (statusCode != 200) {
                    throw new RuntimeException("HTTP " + statusCode + ": " + responseBody);
                }
                return responseBody;
            }
        } catch (Exception e) {
            throw new RuntimeException("Error while sending request: " + e.getMessage(), e);
        }
    }
}
```

***

#### **5. Example API Calls**

**5.1 Get Account Information**

**API Endpoint**: `/api/config`\
**HTTP Method**: `GET`

**Code Example**:

```java
public class Main {
    public static void main(String[] args) {
        try {
            String response = MefreeApiClient.sendRequest("GET", "/api/config");
            System.out.println("Account Information: " + response);
        } catch (Exception e) {
            System.err.println("Failed to fetch account information: " + e.getMessage());
        }
    }
}
```

***

**5.2 Create an Order**

**API Endpoint**: `/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1`\
**HTTP Method**: `POST`

**Code Example**:

```java
public class Main {
    public static void main(String[] args) {
        try {
            String requestPath = "/api/order?quantity=65000&target_address=TRON_ADDRESS&period=1";
            String response = MefreeApiClient.sendRequest("POST", requestPath);
            System.out.println("Order Created: " + response);
        } catch (Exception e) {
            System.err.println("Failed to create order: " + e.getMessage());
        }
    }
}
```

***

**5.3 Query Order Status**

**API Endpoint**: `/api/order/{pay_hash}`\
**HTTP Method**: `GET`

**Code Example**:

```java
public class Main {
    public static void main(String[] args) {
        try {
            String payHash = "abcd1234"; // Replace with actual pay_hash
            String requestPath = "/api/order/" + payHash;
            String response = MefreeApiClient.sendRequest("GET", requestPath);
            System.out.println("Order Status: " + response);
        } catch (Exception e) {
            System.err.println("Failed to fetch order status: " + e.getMessage());
        }
    }
}
```

***

#### **6. Common Issues**

**6.1 Invalid Signature (401 Unauthorized)**

* Ensure the `MF-ACCESS-KEY` matches your API Key.
* Verify the signature generation logic:
  * String concatenation order is `timestamp + method + requestPath`.
  * Use the correct `SECRET_KEY`.
* Ensure the timestamp is in UTC format and not older than 5 seconds.

**6.2 Bad Request (400)**

* Verify the request path and query parameters are correct.
* Ensure `Content-Type` is set to `application/json`.

**6.3 Too Many Requests (429)**

* Respect the API rate limits and implement a delay between requests if necessary.

***

#### **7. Summary**

With this guide, you can now use **Java** to call Mefree.NET APIs. It includes signature generation, HTTP request construction, and example code for various API endpoints. For further clarification, contact Mefree technical support or consult the official API documentation.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mefree.net/getting-started/how-to-buy-energy/java.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
