Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post body is not getting encoded even after adding filter

I have the CharacterEncodingFilter in place(first filter) in web.xml

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

But when I make a POST request, the body does not get encoded Req Body Sent:

{
    "hi": "您好"
}

But received as

{
    "hi": "??"
}
like image 561
barunsthakur Avatar asked Oct 19 '22 17:10

barunsthakur


2 Answers

The CharacterEncodingFilter does not change the encoding of the requests (or response) content, it set only the request/response http-header.

@See code of CharacterEncodingFilter.doFilterInternal(...)

like image 66
Ralph Avatar answered Nov 03 '22 05:11

Ralph


Setting file.encoding to UTF8 in tomcat worked. I don't know why tomcat was not working when system encoding was UTF-8.

According to Java documentation here

The following tables show the encoding sets supported by Java SE 7. The canonical names used by the new java.nio APIs are in many cases not the same as those used in the java.io and java.lang APIs.

like image 29
barunsthakur Avatar answered Nov 03 '22 04:11

barunsthakur