Java中,自签名证书,如果不导入Java环境,那么使用SSL连接的时候,https会报证书验证问题,我们需要实现自己加载证书通过验证。
HTTPS连接:
- HttpsURLConnection con = null;
- BufferedReader in = null;
- try {
-
- FileInputStream fis = new FileInputStream(CERTIFICATE_PATH);
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- keyStore.load(fis, null);
-
- TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
- tmf.init(keyStore);
-
- SSLContext ctx = SSLContext.getInstance("TLS");
- ctx.init(null, tmf.getTrustManagers(), null);
-
- URL obj = new URL(url);
- con = (HttpsURLConnection) obj.openConnection();
- con.setSSLSocketFactory(ctx.getSocketFactory());
-
- con.setRequestMethod("GET");
- con.setRequestProperty("User-Agent", "Mozilla/5.0");
-
- int responseCode = con.getResponseCode();
- System.out.println("Response Code : " + responseCode);
- in = new BufferedReader(new InputStreamReader(con.getInputStream()));
- String inputLine;
- StringBuilder response = new StringBuilder();
- while ((inputLine = in.readLine()) != null) {
- response.append(inputLine);
- }
- return response.toString();
- } catch (Exception e) {
-
- } finally {
- try {
- if (in != null) {
- in.close();
- }
- if (con != null) {
- con.disconnect();
- }
- } catch (IOException e) {
-
- }
- }
使用Apache Http Client库连接场景
- // 使用`loadTrustMaterial()`方法将证书文件加载到信任存储中,传递证书路径、密码和`TrustSelfSignedStrategy`以验证证书
- SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(new File(CERT_PATH), CERT_PASSWORD.toCharArray(), new TrustSelfSignedStrategy()).build();
- HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
- HttpGet httpGet = new HttpGet(URL);
- HttpResponse response = httpClient.execute(httpGet);
- HttpEntity entity = response.getEntity();
- String content = EntityUtils.toString(entity);
使用SSH协议进行连接场景:
- import com.jcraft.jsch.*;
- public class SSHConnection {
- private static final String SERVER_ADDRESS = "example.com";
- private static final String USERNAME = "username";
- private static final String PRIVATE_KEY_PATH = "/path/to/private/key";
- public static void main(String[] args) {
- JSch jsch = new JSch();
- try {
- jsch.addIdentity(PRIVATE_KEY_PATH);
- Session session = jsch.getSession(USERNAME, SERVER_ADDRESS);
-
- session.setConfig("StrictHostKeyChecking", "yes");
- session.connect();
- System.out.println("Connected");
-
- session.disconnect();
- } catch (JSchException e) {
-
- }
- }
- }