0

How to check if account does not exist with the Java SDK? and how to know if a public key is valid?

I found one way to the first question but is not a clean solution

Server server = new Server("https://horizon-testnet.stellar.org");
// It will throw HttpResponseException if account does not exist or there was another error.
    try {
        server.accounts().account("GDCI7LNULXXFMM42JAZ4734YU4IVUJEGOHLQRKPXHYJVZGQPEKNN5NNO");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

When the account does not exist it accuses an exception but I cannot assure that this is the reason that originated it.

So, exist a pre filter to identify in principle if an account's public key does not have the correct format? (to avoid sending the query to the server)

2 Answers 2

2

There is an ErrorResponse exception that you can catch. From the ErrorResponse you will be able to find the status code of the http request. If the status code is 404 then the account does not exist:

            try {
                 server.accounts().account("GDCI7LNULXXFMM42JAZ4734YU4IVUJEGOHLQRKPXHYJVZGQPEKNN5NNO");
            } catch (ErrorResponse e) {
                if (e.getCode() == 404) {
                    // Account does not exist
                }
                throw e;
            }

To check if an account string is a valid public key you can use KeyPair.fromAccountId(). If the account string is invalid KeyPair.fromAccountId() will throw an exception.

0

I found a solution to know if it is a valid address thanks to artificial intelligence:

import org.stellar.sdk.KeyPair;
  private boolean isValidPublicKey(String publicKey) {
    try {
        KeyPair.fromAccountId(publicKey);
        return true;
    } catch (Exception e) {
        return false;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.