From 327cf4dd3d427c668c44119b7213556aaf3d7d7e Mon Sep 17 00:00:00 2001 From: DJ <3272679+smartdj@users.noreply.github.com> Date: Fri, 24 Dec 2021 14:13:09 +0800 Subject: [PATCH] Update HttpClientUtil.java MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修正:responseBody没有关闭导致内存泄漏的问题 修正:抛出异常不够具体 --- .../starter/toolkit/HttpClientUtil.java | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/starter/toolkit/HttpClientUtil.java b/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/starter/toolkit/HttpClientUtil.java index 35c25d07..6ba29b43 100644 --- a/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/starter/toolkit/HttpClientUtil.java +++ b/hippo4j-spring-boot-starter/src/main/java/cn/hippo4j/starter/toolkit/HttpClientUtil.java @@ -165,23 +165,29 @@ public class HttpClientUtil { .url(url) .post(requestBody) .build(); - Response resp = hippo4JOkHttpClient.newCall(request).execute(); - if (resp.code() != HTTP_OK_CODE) { - String msg = String.format("HttpPost 响应 code 异常. [code] %s [url] %s [body] %s", resp.code(), url, jsonBody); - throw new RuntimeException(msg); + try (Response resp = hippo4JOkHttpClient.newCall(request).execute()) { + try (ResponseBody responseBody = resp.body()) { + if (resp.code() != HTTP_OK_CODE) { + String msg = String.format("HttpPost 响应 code 异常. [code] %s [url] %s [body] %s", resp.code(), url, jsonBody); + throw new ResponseStatusException(HttpStatus.valueOf(resp.code()), msg); + } + return resp.body().string(); + } } - return resp.body().string(); } @SneakyThrows private byte[] doGet(String url) { Request request = new Request.Builder().get().url(url).build(); - Response resp = hippo4JOkHttpClient.newCall(request).execute(); - if (resp.code() != HTTP_OK_CODE) { - String msg = String.format("HttpGet 响应 code 异常. [code] %s [url] %s", resp.code(), url); - throw new RuntimeException(msg); + try(Response resp = hippo4JOkHttpClient.newCall(request).execute()){ + try(ResponseBody responseBody = resp.body()){ + if (resp.code() != HTTP_OK_CODE) { + String msg = String.format("HttpGet 响应 code 异常. [code] %s [url] %s", resp.code(), url); + throw new ResponseStatusException(HttpStatus.valueOf(resp.code()), msg); + } + return resp.body().bytes(); + } } - return resp.body().bytes(); } @SneakyThrows