Monday, April 1, 2019

Calling http/https API

The apache httpclient is a de facto standard in calling http within Java.

Here is an excellent introduction with examples: https://www.mkyong.com/java/apache-httpclient-examples/

Now in http calls, you using do POST and GET, and pass parameters like in a html form... sometimes you have to header variables and pass JSON in body too in calling API. The link above provides nice examples. Hard to do from scratch.

What if you have to do https?

Boom! You may get this infamous exception:

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 
The problem here is you need certificates, you can create one with not-so-straightforward commands lines with the keytool command that comes with your JDK. (Go ahead google for it)... and you have to pass in -D parameters in your JDK call.

Or you can choose to allow everything. See this Stackoverflow doc: https://stackoverflow.com/questions/875467/java-client-certificates-over-https-ssl

No comments: