如何用Java发布HTTPS post请求?

时间:2016-12-06 20:49:44

标签: java ssl post https httpsurlconnection

我正在尝试发布HTTPS帖子请求。

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());

我收到以下错误:

  

javax.net.ssl.SSLHandshakeException:   sun.security.validator.ValidatorException:PKIX路径构建失败:   sun.security.provider.certpath.SunCertPathBuilderException:无法   找到所请求目标的有效证书路径   sun.security.ssl.Alerts.getSSLException(Alerts.java:192)at   sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1904)at 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)     在   sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:209)     在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 at   sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1332)     在   sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1359)     在   sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1343)     在   sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)     在   sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)     在   sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1092)     在   sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:250)

请告知导致错误的原因

1 个答案:

答案 0 :(得分:2)

Java无法验证https服务器上SSL证书的有效性。它可以是自签名的,也可以由Java运行时不知道的证书颁发机构签名。

您可以选择通过将证书添加到信任库(cacerts)来手动信任证书,或者让您的证书签名。我不建议完全禁用SSL证书验证,因为您可能会对自己造成意外后果。