From 2c8070f3244284864426d8ba0400def6bbdd6c88 Mon Sep 17 00:00:00 2001 From: Looly Date: Mon, 9 Jun 2025 12:01:29 +0800 Subject: [PATCH] =?UTF-8?q?`HttpConfig`=E5=A2=9E=E5=8A=A0=E5=8F=82?= =?UTF-8?q?=E6=95=B0`setIgnoreContentLength`=E5=8F=AF=E9=80=89=E5=BF=BD?= =?UTF-8?q?=E7=95=A5=E8=AF=BB=E5=8F=96=E5=93=8D=E5=BA=94contentLength?= =?UTF-8?q?=E5=A4=B4=EF=BC=88issue#ICB1B8@Gitee=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 1 + .../main/java/cn/hutool/http/HttpConfig.java | 17 +++++++++++++++++ .../main/java/cn/hutool/http/HttpResponse.java | 3 ++- 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e0168679e..bfebc9bf8 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ * 【ai 】 增加SSE流式返回函数参数callback,豆包、grok新增文生图接口,豆包生成视频支持使用model * 【core 】 DesensitizedUtil新增护照号码脱敏功能(pr#1347@Gitee) * 【core 】 优化XXXToMapCopier的部分性能(pr#1345@Gitee) +* 【http 】 `HttpConfig`增加参数`setIgnoreContentLength`可选忽略读取响应contentLength头(issue#ICB1B8@Gitee) * ### 🐞Bug修复 * 【core 】 修复`NumberUtil`isNumber方法以L结尾没有小数点判断问题(issue#3938@Github) diff --git a/hutool-http/src/main/java/cn/hutool/http/HttpConfig.java b/hutool-http/src/main/java/cn/hutool/http/HttpConfig.java index 172102e45..abc3e02b0 100755 --- a/hutool-http/src/main/java/cn/hutool/http/HttpConfig.java +++ b/hutool-http/src/main/java/cn/hutool/http/HttpConfig.java @@ -101,6 +101,12 @@ public class HttpConfig { */ boolean useDefaultContentTypeIfNull = true; + /** + * 是否忽略Content-Length,如果为true,则忽略Content-Length,自动根据响应内容计算Content-Length
+ * issue#ICB1B8@Gitee,此参数主要解决服务端响应中Content-Length错误的问题 + */ + boolean ignoreContentLength = false; + /** * 设置超时,单位:毫秒
* 超时包括: @@ -332,4 +338,15 @@ public class HttpConfig { this.useDefaultContentTypeIfNull = useDefaultContentTypeIfNull; return this; } + + /** + * 设置是否忽略Content-Length,如果为true,则忽略Content-Length,自动根据响应内容计算Content-Length + * @param ignoreContentLength 是否忽略Content-Length + * @return this + * @since 5.8.39 + */ + public HttpConfig setIgnoreContentLength(boolean ignoreContentLength) { + this.ignoreContentLength = ignoreContentLength; + return this; + } } diff --git a/hutool-http/src/main/java/cn/hutool/http/HttpResponse.java b/hutool-http/src/main/java/cn/hutool/http/HttpResponse.java index 2434e1724..495cc6831 100755 --- a/hutool-http/src/main/java/cn/hutool/http/HttpResponse.java +++ b/hutool-http/src/main/java/cn/hutool/http/HttpResponse.java @@ -664,7 +664,8 @@ public class HttpResponse extends HttpBase implements Closeable { return; } - final long contentLength = contentLength(); + // issue#ICB1B8,如果用户定义忽略contentLength头,则不读取 + final long contentLength = config.ignoreContentLength ? -1 : contentLength(); final FastByteArrayOutputStream out = new FastByteArrayOutputStream((int) contentLength); copyBody(in, out, contentLength, null, this.config.ignoreEOFError); this.body = new BytesResource(out.toByteArray());