[#5861] HttpUtil.getContentLength(HttpMessage, long) throws unexpected NumberFormatException

Motivation:

The Javadocs of HttpUtil.getContentLength(HttpMessage, long) and its int overload state that the provided default value is returned if the Content-Length value is not a number. NumberFormatException is thrown instead.

Modifications:

Correctly handle when the value is not a number.

Result:

API works as stated in javadocs.
This commit is contained in:
Norman Maurer 2016-09-27 05:50:14 +02:00
parent 20da5383ce
commit cf8f6e3e2f
2 changed files with 14 additions and 1 deletions

View File

@ -184,7 +184,11 @@ public final class HttpUtil {
public static long getContentLength(HttpMessage message, long defaultValue) { public static long getContentLength(HttpMessage message, long defaultValue) {
String value = message.headers().get(HttpHeaderNames.CONTENT_LENGTH); String value = message.headers().get(HttpHeaderNames.CONTENT_LENGTH);
if (value != null) { if (value != null) {
return Long.parseLong(value); try {
return Long.parseLong(value);
} catch (NumberFormatException ignore) {
return defaultValue;
}
} }
// We know the content length if it's a Web Socket message even if // We know the content length if it's a Web Socket message even if

View File

@ -100,4 +100,13 @@ public class HttpUtilTest {
message.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8"); message.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8");
assertEquals("text/html", HttpUtil.getMimeType(message)); assertEquals("text/html", HttpUtil.getMimeType(message));
} }
@Test
public void testGetContentLengthDefaultValue() {
HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
assertNull(message.headers().get(HttpHeaderNames.CONTENT_LENGTH));
message.headers().set(HttpHeaderNames.CONTENT_LENGTH, "bar");
assertEquals("bar", message.headers().get(HttpHeaderNames.CONTENT_LENGTH));
assertEquals(1L, HttpUtil.getContentLength(message, 1L));
}
} }