I'm using the code below to send an OTP
but I'm receiving an error:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at responseMessage = connection.getResponseMessage();
I've found couple of solutions but not sure about the implementation of the answers.
public Boolean sendSmsOTP(String MobileNumber, String OTPKey) {
logDebugInfo("In sendSmsOTP ", LOG_TYPE_INFORMATIVE);
HttpURLConnection connection;
int responseCode;
String requestData, responseMessage;
URL smsUrl;
URI uri;
String mobileNumber = MobileNumber.replace("+91", "");
try {
logDebugInfo("Mobile Number : " + mobileNumber + " OTP : " + OTPKey, LOG_TYPE_INFORMATIVE);
requestData = gResourceBundle.getString("RequestSMSData");
requestData = requestData.replace("[MobileNumber]", mobileNumber.trim());
requestData = requestData.replace("[OTPKEY]", OTPKey);
requestData = requestData.replace("[ ]", "%20");
requestData = requestData.replace(" ", "%20");
System.out.println(requestData.toString());
uri = new URI(requestData);
smsUrl = uri.toURL();
logDebugInfo("URL : " + smsUrl.toString(), LOG_TYPE_INFORMATIVE);
connection = (HttpURLConnection) smsUrl.openConnection();
connection.setDoOutput(false);
connection.setDoInput(true);
System.out.println("Manish negi -> "+connection.toString());
responseMessage = connection.getResponseMessage();
logDebugInfo("Response Message from SMS server " + responseMessage, LOG_TYPE_INFORMATIVE);
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
connection.disconnect();
System.out.println("OTP GENERATED");
return true;
} else {
connection.disconnect();
return false;
}
} catch (Exception e) {
logErrorInfo("Exception in sendSmsOTP function()..." + e.getMessage());
logDebugInfo("Exception in sendSmsOTP function()..." + e.getMessage(), LOG_TYPE_CRITICAL);
gResultMessage = gResultMessage.replace("Error Code", "CA01");
gReturnResponse = getJSONString(gErrorResponse, gResultMessage);
e.printStackTrace();
return false;
}
}
In my experience this error message often means that you are trying to establish a TLS connection to a server with a self-signed certificate. If that is the case here, the solution usually is to add the server's certificate to the certificate store of the JVM your client is running on.
If you have the certificate in a file called server.crt
, you can add it using the keytool
that comes with the JVM, like this:
keytool -import -noprompt \
-storepass changeit \
-alias some_alias \
-keystore $JAVA_HOME/jre/lib/security/cacerts \
-file server.crt
You can obtain the server's certificate using openssl
with a command like this:
openssl s_client -showcerts -connect www.example.com:443 </dev/null