问题
I'm trying to make a HTTPS post request.
String url = "https://myhttpsurl.com"
URL myurl = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();
con.setRequestMethod("POST");
String query = "confirmation_number=" + URLEncoder.encode(confNumber, "UTF-8");
con.setRequestProperty("Content-length",String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes(query);
output.close();
System.out.println("Resp Code:"+con.getResponseCode());
I'm getting the following error:
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:1904) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:279) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:273) at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1446) at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:209) at sun.security.ssl.Handshaker.processLoop(Handshaker.java:913) at sun.security.ssl.Handshaker.process_record(Handshaker.java:849) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1023) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1359) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1343) at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1092) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)
Please suggest what is causing the error
回答1:
Java is not able to verify the validity of the SSL certificate on the https server. It is either self-signed or signed by a certificate authority not known to the Java runtime.
Your options are to manually trust the certificate by adding it to the truststore (cacerts), or to have your certificate signed. I don't recommend disabling the SSL certificate validation completely, as you might open yourself to unexpected consequences.
来源:https://stackoverflow.com/questions/41004619/how-to-make-https-post-request-in-java