在https请求中发送.crt证书

时间:2018-12-18 05:30:04

标签: java https certificate ssl-certificate

我是证书概念的新手,可以帮助任何人如何在https请求中发送证书。 我的CURL命令如下:

curl -d "grant_type=password&client_id=SmartRest&client_secret=594a27f3-4432-4d37-9196-2ba49de52758&username=user123&password=welcome123" https://xxxxxxx.xxx.in:8543/auth/realms/restapi/protocol/openid-connect/token --cacert ./ca_bundle.crt

我需要在Java代码中发送同样的内容,我只有一个.crt文件,我没有密钥密码或任何东西。

1 个答案:

答案 0 :(得分:0)

我通过以下keytool命令信任了证书。

keytool -import -trustcacerts -file "ca_bundle.crt" -alias "alias" -keystore  "C:\Program Files\Java\jdk1.8.0_131\jre\lib\security\cacerts"

下面的代码工作正常,无需跳过ssl验证。

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

   HttpsURLConnection con = (HttpsURLConnection) new URL("https://xxxx.xxx.xx:8543/auth/realms/restapi/protocol/openid-connect/token").openConnection();
   con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
   String urlParameters = "grant_type=password&client_id=SmartRest&client_secret=594a27f3-4432-4d37-9196-2ba49de52758&username=user123&password=welcome123";

   con.setDoOutput(true);
   DataOutputStream wr = new DataOutputStream(con.getOutputStream());
   wr.writeBytes(urlParameters);
   wr.flush();
   wr.close();

   BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
   String inputLine;
   StringBuffer response = new StringBuffer();

   while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
   }
   in.close();

   //print result
   System.out.println(response.toString());

}

我得到了结果。