来自HTTPS的Java post方法

时间:2015-03-16 14:04:00

标签: java https cryptography

我在https页面中遇到问题ia使用此代码

 URL url = new URL("https://<website>.aspx?g=postmessage&f=234");
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("forum:_ctl0:Subject", filName);
    params.put("forum:_ctl0:edit", numcert );


    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
    conn.setDoOutput(true);
    conn.getOutputStream().write(postDataBytes);

    Reader in = new BufferedReader(new
    InputStreamReader(conn.getInputStream(), "UTF-8"));
    for (int c; (c = in.read()) >= 0; System.out.print((char)c));
  }

当我运行它时,它会给我错误

 Exception in thread "main" 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(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
at single_window.my.MainWatch.Trup(MainWatch.java:51)
at single_window.my.MainWatch.main(MainWatch.java:99)
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(Unknown Source)
 at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
 at sun.security.validator.Validator.validate(Unknown Source)
 at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
 at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
 at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 15 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException:
unable to
find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown
Source)
 at java.security.cert.CertPathBuilder.build(Unknown Source)
 ... 21 more

我在循环中使用了

的方法
public static void main(String[] args)throws Exception {

    Path faxFolder = Paths.get("\\test\\in");
    WatchService watchService = FileSystems.getDefault().newWatchService();
    faxFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);


    boolean valid = true;
    do {
        WatchKey watchKey = watchService.take();

        for (WatchEvent event : watchKey.pollEvents()) {
            WatchEvent.Kind kind = event.kind();
            if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
                String fileName = event.context().toString();

                 for (File myFile : new File("\\test\\in").listFiles()){



                            User user=null;
                            ObjectMapper mapper= new ObjectMapper();
                            user=mapper.readValue(myFile, User.class);
                            //System.out.println
                            numcert=(user.getNum());
                            filName = fileName.substring(0, fileName.length()-14);
                            //System.out.println(filName);
                            delay(2000);
                            Trup();
                            delay(5000);
                            Path original = Paths.get("\\test\\in\\"+myFile.getName()); 
                            Path destination = Paths.get("\\test\\out\\"+myFile.getName()); 

                             Files.move(original, destination, StandardCopyOption.REPLACE_EXISTING); 






                 }

                //JOptionPane.showMessageDialog(null,"File Created:" + fileName);
            }
        }
        valid = watchKey.reset();

    } while (valid);

}

2 个答案:

答案 0 :(得分:1)

如果您的HTTPS未经过认证,或者您的系统不允许,则需要像浏览时一样进入受信任区域。不同之处在于您使用JDK附带的keytool。您可以在网上找到许多这个过程的教程。

发生SSLHandshakeException时,通常会出现问题,或者认证已过期。

答案 1 :(得分:1)

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

这意味着您连接的Web服务器或URL没有来自授权CA的有效证书。但是,作为程序员,您可能希望找到解决此问题的替代方法。

您需要做的是导入服务器证书并将其安装在JDK的密钥存储区中。只需按照这些步骤操作,您就可以摆脱该错误。

  1. 首先,您复制要连接的网址并将其粘贴到浏览器中。我们假设你正在使用IE浏览器。只需将网址粘贴到地址栏中,然后按Enter键。

  2. 您现在可能会看到一个警告您有关证书的对话框。现在单击“查看证书”并安装证书。忽略任何警告信息。

  3. 现在计算机中已安装服务器证书,当您再次访问同一站点时,浏览器不会向您发出警告。但是你的JRE是愚蠢的,因为它直到你把它添加到它的密钥库之前还不知道这个证书的存在。通常,您将使用密钥工具来管理证书。密钥工具是一个命令行实用程序,具有多个参数,允许您创建和管理用于容纳数字证书的密钥库。有关密钥工具的完整文档,请参阅:http://java.sun.com/j2se/1.3/docs/tooldocs/win32/keytool.html

  4. 您可以使用key-tool -list命令列出密钥库中包含的当前证书。 cacerts密钥库的初始密码是更改它。例如:

    C:\Program Files\Citrix\Citrix Extranet Server\SGJC\jre\bin>keytool -list -keystore ..\lib\security\cacerts
    
    Enter keystore password: changeit
    

    然后你会看到类似的东西:

    Keystore type: jks
    Keystore provider: SUN
    Your keystore contains 11 entries:
    engweb, Wed Apr 11 16:22:49 EDT 2001, trustedCertEntry,
    
    Certificate fingerprint (MD5): 8C:24:DA:52:7A:4A:16:4B:8E:FB:67:44:C9:D2:E4:16
    
    thawtepersonalfreemailca, Fri Feb 12 15:12:16 EST 1999, trustedCertEntry,
    
    Certificate fingerprint (MD5): 1E:74:C3:86:3C:0C:35:C5:3E:C2:7F:EF:3C:AA:3C:D9
    
    thawtepersonalbasicca, Fri Feb 12 15:11:01 EST 1999, trustedCertEntry,
    
    Certificate fingerprint (MD5): E6:0B:D2:C9:CA:2D:88:DB:1A:71:0E:4B:78:EB:02:41
    
    verisignclass3ca, Mon Jun 29 13:05:51 EDT 1998, trustedCertEntry,
    
    Certificate fingerprint (MD5): 78:2A:02:DF:DB:2E:14:D5:A7:5F:0A:DF:B6:8E:9C:5D
    
    thawteserverca, Fri Feb 12 15:14:33 EST 1999, trustedCertEntry,
    
    Certificate fingerprint (MD5): C5:70:C4:A2:ED:53:78:0C:C8:10:53:81:64:CB:D0:1D
    
    thawtepersonalpremiumca, Fri Feb 12 15:13:21 EST 1999, trustedCertEntry,
    
    Certificate fingerprint (MD5): 3A:B2:DE:22:9A:20:93:49:F9:ED:C8:D2:8A:E7:68:0D
    
    verisignclass4ca, Mon Jun 29 13:06:57 EDT 1998, trustedCertEntry,
    
    Certificate fingerprint (MD5): 1B:D1:AD:17:8B:7F:22:13:24:F5:26:E2:5D:4E:B9:10
    
    verisignclass1ca, Mon Jun 29 13:06:17 EDT 1998, trustedCertEntry,
    
    Certificate fingerprint (MD5): 51:86:E8:1F:BC:B1:C3:71:B5:18:10:DB:5F:DC:F6:20
    
    verisignserverca, Mon Jun 29 13:07:34 EDT 1998, trustedCertEntry,
    
    Certificate fingerprint (MD5): 74:7B:82:03:43:F0:00:9E:6B:B3:EC:47:BF:85:A5:93
    
    thawtepremiumserverca, Fri Feb 12 15:15:26 EST 1999, trustedCertEntry,
    
    Certificate fingerprint (MD5): 06:9F:69:79:16:66:90:02:1B:8C:8C:A2:C3:07:6F:3A
    
    verisignclass2ca, Mon Jun 29 13:06:39 EDT 1998, trustedCertEntry,
    
     Certificate fingerprint (MD5): EC:40:7D:2B:76:52:67:05:2C:EA:F2:3A:4F:65:F0:D8
    
  5. 现在您必须将预先安装的证书添加到此密钥库。要添加,首先将CA根证书导出为DER编码的二进制文件,然后将其另存为C:\root.cer。 (您可以在

  6. 下查看已安装的证书
      

    工具 - &gt;'互联网选项' - &gt;内容 - &gt;证书。

    打开证书后,找到刚刚安装在“受信任的根证书颁发机构”下的证书。选择正确的证书并单击“导出”。现在可以将它(DER编码的二进制文件)保存在c:驱动器下。

    1. 然后使用keytool -import命令将文件导入cacerts密钥库。例如:

      -alias myprivateroot -keystore ..\lib\security\cacerts -file c:\root.cer
      
      Enter keystore password: changeit
      
      Owner: CN=Division name, OU=Department, O=Your Company, L=Anytown,   ST=NC, C=US, EmailAddress=you@company.com
      
      Issuer: CN=Division name, OU=Department, O=Your Company, L=Anytown, ST=NC, C=US, EmailAddress=you@company.com
      
      Serial number: 79805d77eecfadb147e84f8cc2a22106
      
      Valid from: Wed Sep 19 14:15:10 EDT 2001 until: Mon Sep 19 14:23:20 EDT 2101
      
      Certificate fingerprints:
      
      MD5: B6:30:03:DC:6D:73:57:9B:F4:EE:13:16:C7:68:85:09
      
      SHA1: B5:C3:BB:CA:34:DF:54:85:2A:E9:B2:05:E0:F7:84:1E:6E:E3:E7:68
      
      Trust this certificate? [no]: yes
      
      Certificate was added to keystore
      
    2. 现在再次运行keytool -list以验证您的私有根证书是否已添加:

      C:\Program Files\Citrix\Citrix Extranet Server\SGJC\jre\bin>keytool -list -keystore ..\lib\security\cacerts
      
    3. 现在,您将看到所有证书的列表,包括您刚刚添加的证书。

      这确认您的私有根证书已作为受信任的证书颁发机构添加到Extranet服务器cacerts密钥库。

      有关详细信息,请访问以下网址:

      http://www.java-samples.com/showtutorial.php?tutorialid=210

相关问题