Java JSON Working Sample

  • 1
  • Question
  • Updated 2 months ago
Is there a simple working Java sample of a JSON call using the Rest API, demonstrating how to include credentials?  I have searched high and low to no avail.  I see the demos, but that only shows me the JSON request structure for the transaction.
https://developer.avalara.com/api-reference/avatax/rest/v2/methods/Transactions/CreateTransaction/

How do I assemble the username/password and send that off to:
https://sandbox-rest.avatax.com/api/v2/transactions/create

I feel like with one working sample of seeing JSON go out, and be returned, I can flesh out my whole solution.  But I am stuck just sending anything back and forth.



Photo of Robert Mazur

Robert Mazur

  • 9 Posts
  • 0 Reply Likes

Posted 2 months ago

  • 1
Photo of Robert Mazur

Robert Mazur

  • 9 Posts
  • 0 Reply Likes
In case you are wondering what I have tried...

I have tried a simple Ping attempt which eventually I would change to JSON going outbound:
    public void tryRest() {
        try {

            URL url = new URL("https://sandbox-rest.avatax.com/api/v2/utilities/ping");
           
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP Error code : "
                        + conn.getResponseCode());
            }
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(in);
            String output;
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            conn.disconnect();

        } catch (Exception e) {
            System.out.println("Exception in NetClientGet:- " + e);
        }
    }



And I have tried using the SDK with sample code fetched from the Avalara website:

    public void trySDKClient() {           
        try {
        //creates our AvaTaxClient
        AvaTaxClient client = new AvaTaxClient("Test", "1.0", "https://rest.avatax.com/api/v2/transactions/create";, AvaTaxEnvironment.Production)
            .withSecurity("MyRealUserName", "MyRealPassword");
        // build and create transaction
        TransactionModel transactionModel = new TransactionBuilder(client, "DEFAULT", DocumentType.SalesOrder, "ABC")
            .withAddress(TransactionAddressType.ShipFrom, "255 S. King Street", null, null, "Seattle", "WA", "98104", "US")
            .withAddress(TransactionAddressType.ShipTo, "512 S Mangum Street", null, null, "Durham", "NC", "27701", "US")
            .withLine("1", new BigDecimal(40.21), null, "PC040400", null, null, null, null, null,"null")
            .Create();
       
   
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }



In both cases I am getting a similar response:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Photo of Chris Walker

Chris Walker, Official Rep

  • 25 Posts
  • 2 Reply Likes
It looks like you are passing the url of the endpoint when instantiating the AvaTaxClient you should be following this model:

AvaTaxClient client = new AvaTaxClient("yourAppName", "yourVersion", "yourMachineName", AvaTaxEnvironment.Sandbox)
               .withSecurity("username","password");

Try running this code below and see if you get a successful result.
AvaTaxClient client = new AvaTaxClient("Test", "1.0", "localhost", AvaTaxEnvironment.Sandbox)
   .withSecurity("MyUsername", "MyPassword"); //replace with your username and password
		
try {
   //verify that we can ping successfully
	PingResultModel ping = client.ping();
	if(ping.getAuthenticated()) {
		System.out.print("Successfully created a client!");
	}
} catch (Exception e) {}		
		



Photo of Robert Mazur

Robert Mazur

  • 9 Posts
  • 0 Reply Likes
Thank you for the response, Chris.

After substituting in my user/pass, I am catching an exception.  I have included much of it below, very similar to the result of my other efforts.  Does this look like a user/pass issue to you?

For the record, I can use my user/pass to successfully log in here:
sandbox.admin.avalara.com

Thoughts?
Rob

----------------
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1917)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:301)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:295)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1471)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:212)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:936)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:871)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:394)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:353)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:141)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
    at net.avalara.avatax.rest.client.RestCall.call(RestCall.java:87)
    at net.avalara.avatax.rest.client.AvaTaxClient.ping(AvaTaxClient.java:17229)
    at com.sffnw.test.AvalaraTest.trySDKClient2(AvalaraTest.java:262)
    at com.sffnw.test.AvalaraTest.main(AvalaraTest.java:44)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
    at sun.security.validator.Validator.validate(Validator.java:260)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1453)


Photo of Robert Mazur

Robert Mazur

  • 9 Posts
  • 0 Reply Likes
Hi Chris,

Please pause your efforts to address my error above related to javax.net.ssl.SSLHandshakeException.  Evidently there is an issue when trying to run this on Ubuntu (which I am):
https://stackoverflow.com/questions/13626965/how-to-ignore-pkix-path-building-failed-sun-security-pr...

There are fixes, but to resolve for now, I moved to OS X, and also had to bring my Apache Commons Codec up to date to 1.13.  I can now successfully create the Client.

I will carry on from here to try to turn some basic transactions.  I hope I may be able to ask further questions, if need be.

Thank you,
Rob

Photo of Robert Mazur

Robert Mazur

  • 9 Posts
  • 0 Reply Likes
Hi Chris,

I have two follow-up questions, both quick and related to Java so I will keep them in this thread.

1) SDK vs. REST - I have tried without success for sometime to get a "hello world" to your web service working with JAVA/JSON/REST.  I see tons of REST body snippets all throughout the docs (and that's great), but not one that shows me how to authenticate with your services.  For this successful Java SDK ping below, can you please tell me what the equivalent would be for JAVA and JSON querying your REST service?  I'd paste here what I have tried, but think it best not to litter the thread with unsuccessful attempts.

public void pingOnly() {
    AvaTaxClient client = new AvaTaxClient("Test", "1.0", "localhost", AvaTaxEnvironment.Sandbox)
    .withSecurity("MyUser", "MyPass"); //replace with your username and password

    try {
        //verify that we can ping successfully
        PingResultModel ping = client.ping();
        if(ping.getAuthenticated()) {
            System.out.println("Successfully created a client!");
        }
        else {
            System.out.println("Not getting authentication");
        }
    }
    catch (Exception e) {
         e.printStackTrace();
    }
}

2) SDK DOCUMENTATION - Since we are leaning the route of using the Java SDK, can you please tell me where I can find API documentation for it?  I see endless docs for what is available through the REST interface, lots of code snippets.  But I am not seeing a JAVA API so that I know what these classes and methods do, as well as what the method parameters are asking for.

Is there a PDF or browser based docs for the Java SDK?

Thank you much,
Rob