/** * A http content type should contain a character set like * "application/json; charset=utf-8". * * If you only want to get the character set you can use this method. * * See also: http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1 * * @param rawContentType "application/json; charset=utf-8" or "application/json" * @return only the character set like utf-8 OR utf-8 when not set */ public static String getCharsetOfContentTypeOrUtf8(String rawContentType) { return getCharsetOfContentType(rawContentType, NinjaConstant.UTF_8); }
/** * When a servlet engine gets a content type like: "application/json" it * assumes a default encoding of iso-xxxxx. * * That is not what Ninja does (and is not consistent with default encodings * of application/json and application/xml). * * Therefore we'll set utf-8 as request encoding if it is not set. */ private void enforceCorrectEncodingOfRequest() { String charset = NinjaConstant.UTF_8; String contentType = getHeader(CONTENT_TYPE); if (contentType != null) { charset = HttpHeaderUtils.getCharsetOfContentTypeOrUtf8(contentType); } try { httpServletRequest.setCharacterEncoding(charset); } catch (UnsupportedEncodingException e) { logger.error("Server does not support charset of content type: " + contentType); } }
@Override public <T> T parseBody(Class<T> classOfT) { String rawContentType = getRequestContentType(); // If the Content-type: xxx header is not set we return null. // we cannot parse that request. if (rawContentType == null) { logger.debug("Not able to parse body because request did not send content type header at: {}", getRequestPath()); return null; } // If Content-type is application/json; charset=utf-8 we split away the charset // application/json String contentTypeOnly = HttpHeaderUtils.getContentTypeFromContentTypeAndCharacterSetting( rawContentType); BodyParserEngine bodyParserEngine = bodyParserEngineManager .getBodyParserEngineForContentType(contentTypeOnly); if (bodyParserEngine == null) { logger.debug("No BodyParserEngine found for Content-Type {} at route {}", contentTypeOnly, getRequestPath()); return null; } return bodyParserEngine.invoke(this, classOfT); }
charset = HttpHeaderUtils.getCharsetOfContentTypeOrUtf8(contentType);