Java使用客户端身份验证发送HTTP Post

时间:2018-10-28 02:12:28

标签: java ssl apache-httpclient-4.x

我有一个客户端证书,密钥和证书可以使用。我想要的代码的卷曲将是
curl https:<ip>/query --cert client_cert.pem --key client_key.pem --cacert ca_cert.pem "-d <post data>"

我已尝试将这些文件合并为PFX(和p12),因为这似乎是必需的格式,但是我不确定我是否正确执行了此操作:

openssl pkcs12 -export -out client.pfx -inkey client_key.pem -in client_cert.pem -certfile ca_cert.pem  

我最初收到有关在我的证书中未定义SAN的错误,此后我添加了一些应忽略此错误的代码,但我认为这不是造成我问题的原因。当卷曲给我实际期望的内容时,我从POST收到404结果

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(new FileInputStream("client.pfx"), keyPassphrase.toCharArray());                                                                      


    SSLContext sslContext = SSLContexts.custom()
        .loadKeyMaterial(keyStore, keyPassphrase.toCharArray())
        .loadTrustMaterial(keyStore, TrustSelfSignedStrategy.INSTANCE)
        .build();

    HttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).setSSLContext(sslContext).build();                                  
    HttpPost httpPost = new HttpPost("https://" + ip + "/query");
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(postKey, postVal));

    httpPost.setEntity(new UrlEncodedFormEntity(params));

    HttpResponse response = httpClient.execute(httpPost);
    System.out.println(response.toString());

给予

HttpResponseProxy{HTTP/1.1 404 Not Found [Date: Sun, 28 Oct 2018 02:11:55 GMT, Server: Apache/2.4.29 (Ubuntu), Content-Length: 280, Keep-Alive: timeout=5, max=100, Connection: Keep-Alive, Content-Type: text/html; charset=iso-8859-1] ResponseEntityProxy{[Content-Type: text/html; charset=iso-8859-1,Content-Length: 280,Chunked: false]}} 

任何想法,如果我的代码是错误的,或者是证书还是什么?据我所知,我正确地制作了pfx,并且如果curl有效,则证书显然可以正常工作。我已经为此工作了一段时间,但无法弄清楚。

编辑:由于我的调试,原始代码(“ https //”与“ https://”)是堆栈溢出的错字。那不是问题。

1 个答案:

答案 0 :(得分:1)

在https后面添加一个冒号(:)。

HttpPost httpPost = new HttpPost("https//" + ip + "/query");    // old
HttpPost httpPost = new HttpPost("https://" + ip + "/query");   // new