diff --git a/hutool-http/src/main/java/org/dromara/hutool/http/meta/ContentType.java b/hutool-http/src/main/java/org/dromara/hutool/http/meta/ContentType.java index fcc7a56c9..9a822597b 100644 --- a/hutool-http/src/main/java/org/dromara/hutool/http/meta/ContentType.java +++ b/hutool-http/src/main/java/org/dromara/hutool/http/meta/ContentType.java @@ -132,7 +132,7 @@ public enum ContentType { public static ContentType get(final String body) { ContentType contentType = null; if (StrUtil.isNotBlank(body)) { - final char firstChar = body.charAt(0); + final char firstChar = StrUtil.trimPrefix(body).charAt(0); switch (firstChar) { case '{': case '[': diff --git a/hutool-http/src/test/java/org/dromara/hutool/http/ContentTypeTest.java b/hutool-http/src/test/java/org/dromara/hutool/http/ContentTypeTest.java index 48a294fb5..2e1678446 100644 --- a/hutool-http/src/test/java/org/dromara/hutool/http/ContentTypeTest.java +++ b/hutool-http/src/test/java/org/dromara/hutool/http/ContentTypeTest.java @@ -14,9 +14,12 @@ package org.dromara.hutool.http; import org.dromara.hutool.core.util.CharsetUtil; import org.dromara.hutool.http.meta.ContentType; +import org.junit.Assert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * ContentType 单元测试 * @@ -26,6 +29,15 @@ public class ContentTypeTest { @Test public void testBuild() { final String result = ContentType.build(ContentType.JSON, CharsetUtil.UTF_8); - Assertions.assertEquals("application/json;charset=UTF-8", result); + assertEquals("application/json;charset=UTF-8", result); + } + + @Test + void testGetWithLeadingSpace() { + final String json = " {\n" + + " \"name\": \"hutool\"\n" + + " }"; + final ContentType contentType = ContentType.get(json); + assertEquals(ContentType.JSON, contentType); } }