From a5faee0bf110843f7a5293e43f547bccdef54956 Mon Sep 17 00:00:00 2001 From: Arthur Ming Date: Tue, 13 Feb 2024 18:33:46 +0800 Subject: [PATCH] refactor: use try with resource to build http client --- .../jobs/service/impl/RepoServiceImpl.java | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/daming/jobs/service/impl/RepoServiceImpl.java b/src/main/java/org/daming/jobs/service/impl/RepoServiceImpl.java index c423895..37530ed 100644 --- a/src/main/java/org/daming/jobs/service/impl/RepoServiceImpl.java +++ b/src/main/java/org/daming/jobs/service/impl/RepoServiceImpl.java @@ -14,6 +14,7 @@ import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; +import java.security.cert.X509Certificate; import java.time.Duration; @Service @@ -24,31 +25,32 @@ public String listCommits() throws IOException, InterruptedException, NoSuchAlgo var url = "https://api.github.com/repos/damingerdai/jobs/commits"; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, getTrustAllCerts(), new SecureRandom()); - var client = HttpClient + try (var client = HttpClient .newBuilder() .sslContext(sslContext) - .build();; - var request = HttpRequest.newBuilder() - .uri(URI.create(url)) - .timeout(Duration.ofMinutes(1)) - .GET() - .timeout(Duration.ofMinutes(1)) - .build(); - var response = client.send(request, HttpResponse.BodyHandlers.ofString()); - return response.body(); + .build()){ + var request = HttpRequest.newBuilder() + .uri(URI.create(url)) + .timeout(Duration.ofMinutes(1)) + .GET() + .timeout(Duration.ofMinutes(1)) + .build(); + var response = client.send(request, HttpResponse.BodyHandlers.ofString()); + return response.body(); + } } private TrustManager[] getTrustAllCerts() { return new TrustManager[]{ new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { + public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) { + X509Certificate[] certs, String authType) { } public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) { + X509Certificate[] certs, String authType) { } } };