来自 HTTPS 的 Java post 方法

标签 java https cryptography

我在 https 页面中使用 POST 时遇到问题,请使用此代码

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

}

最佳答案

如果您的 HTTPS 未经过认证,或者您的系统不允许,您需要像您浏览的那样将其放入信任区域。不同之处在于您使用 JDK 附带的 keytool。您可以在网上找到许多有关此过程的教程。

当发生 SSLHandshakeException 时,通常就是这个问题,或者认证已过期。

关于来自 HTTPS 的 Java post 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29078772/

相关文章:

javascript - 实现复杂 REST 调用的最佳实践是什么?

cryptography - SHA1 在 PBKDF2 中用作散列函数是否仍然安全?

python - AES:如何检测输入了错误的密码?

java - 计算所有奇数数组索引的总和

java - 如何从类中绘制形状到小程序?

java - 如何使用 Java 机器人类获取按键欧洲 "è"字符

Java Json/Gson 将 json 编码的字符串放入 jsonObject 中,不进行字符串转义

node.js - 如何从 node.js 连接到 Tor 网桥?

java - 在反向代理后面需要 HTTPS 和 Spring Security

c# - C# 中的“向后”公钥/私钥加密,我该怎么做?