0

I'm trying to get file name from request header, I'm getting character encoding problem despite I have defined Spring encoding filter in my web.xml.

String fileName = request.getHeader("X-File-Name"); // wrong encoding

web.xml

        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Also I've added URIEncoding="UTF-8" config into Tomcat server.xml file. And added same config JAVA_OPTS too.

-DuriEncoding=UTF-8 -Dfile.encoding=UTF-8

2 Answers 2

2

Well if the headers are always in UTF-8 (or ascii otherwise), you could do this:

public static String reEncode( String input ) {
    Charset w1252 = Charset.forName("Windows-1252"); //Superset of ISO-8859-1
    Charset utf8 = Charset.forName("UTF-8");
    return new String(input.getBytes(w1252), utf8 );
}

...

String fileName = reEncode("Mekanizması.pdf"); //request.getHeader("X-File-Name")
System.out.println(fileName); //Mekanizması.pdf
Sign up to request clarification or add additional context in comments.

3 Comments

thank you so much Esailija for your help, now I'm able to get the right value.
Very brittle, since there so char encoding guarantee for HTTP headers.
@Michael-O yes, that's why it says either UTF-8 or ASCII. If it's in some other random encoding, he will see mojibake. I would recommend a normal query parameter as well, fwiw.
0

There is no encoding defined for HTTP headers. Expect them to support at most ISO-8859-1. Better rely on US-ASCII. The param is, as the name says, for URIs and their params. Nothing else.

4 Comments

I see, so how can I get the right value of file from HTTP-Header?
@talha06 what is the value you are getting now?
for example I'm getting "Onay Mekanizması.pdf" instead of "Onay Mekanizması.pdf" which is the right file name.
Forget about the header. ARe you performing a PUT?. If yes, use the URI. This is the only safe way. If you are POSTing with multipart. This works automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.