Fix HttpUtil.getCharset to not throw illegal charset exception (#9439)

Motivation:

If the HttpUtil.getCharset method is called with an illegal charset like
"charset=!illegal!" it throws an IllegalCharsetNameException. But the javadoc
states, that defaultCharset is returned if incorrect header value. Since the
client sending the request sets the header value this should not crash.

Modification:

HttpUtil.getCharset catches the IllegalCharsetNameException and returns the
defualt value.

Result:

HttpUtil.getCharset does not throw IllegalCharsetNameException any more.
This commit is contained in:
noSim 2019-08-10 19:16:12 +02:00 committed by Norman Maurer
parent 3f0f322562
commit cbc8fc4428
2 changed files with 15 additions and 5 deletions

View File

@ -18,6 +18,7 @@ package io.netty.handler.codec.http;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.Iterator;
@ -391,15 +392,14 @@ public final class HttpUtil {
if (charsetCharSequence != null) {
try {
return Charset.forName(charsetCharSequence.toString());
} catch (IllegalCharsetNameException ignored) {
// just return the default charset
} catch (UnsupportedCharsetException ignored) {
return defaultCharset;
// just return the default charset
}
} else {
return defaultCharset;
}
} else {
return defaultCharset;
}
return defaultCharset;
}
/**

View File

@ -109,6 +109,7 @@ public class HttpUtilTest {
public void testGetCharset_defaultValue() {
final String SIMPLE_CONTENT_TYPE = "text/html";
final String CONTENT_TYPE_WITH_INCORRECT_CHARSET = "text/html; charset=UTFFF";
final String CONTENT_TYPE_WITH_ILLEGAL_CHARSET_NAME = "text/html; charset=!illegal!";
HttpMessage message = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
message.headers().set(HttpHeaderNames.CONTENT_TYPE, SIMPLE_CONTENT_TYPE);
@ -127,6 +128,15 @@ public class HttpUtilTest {
assertEquals(CharsetUtil.UTF_8, HttpUtil.getCharset(message, StandardCharsets.UTF_8));
assertEquals(CharsetUtil.UTF_8,
HttpUtil.getCharset(CONTENT_TYPE_WITH_INCORRECT_CHARSET, StandardCharsets.UTF_8));
message.headers().set(HttpHeaderNames.CONTENT_TYPE, CONTENT_TYPE_WITH_ILLEGAL_CHARSET_NAME);
assertEquals(CharsetUtil.ISO_8859_1, HttpUtil.getCharset(message));
assertEquals(CharsetUtil.ISO_8859_1, HttpUtil.getCharset(CONTENT_TYPE_WITH_ILLEGAL_CHARSET_NAME));
message.headers().set(HttpHeaderNames.CONTENT_TYPE, CONTENT_TYPE_WITH_ILLEGAL_CHARSET_NAME);
assertEquals(CharsetUtil.UTF_8, HttpUtil.getCharset(message, StandardCharsets.UTF_8));
assertEquals(CharsetUtil.UTF_8,
HttpUtil.getCharset(CONTENT_TYPE_WITH_ILLEGAL_CHARSET_NAME, StandardCharsets.UTF_8));
}
@Test