Jersey and @FormParam not working when charset is specified in the Content-Type

后端 未结 2 1715
-上瘾入骨i
-上瘾入骨i 2020-12-09 00:40

It seems like Jersey 2.0 (using servlet 3.1) is not able to decode a parameter when the charset property is specified in the Content-Type header.

2条回答
  •  忘掉有多难
    2020-12-09 01:05

    Here is a simple work-around inspired by Carlo's post. The only modification is to match '; charset=UTF-8'; otherwise, 'multipart/form-data; boundary=...' content types fail.

    // IMPLEMENTATION NOTE: Resolves an issue with FormParam processing
    // @see https://java.net/jira/browse/JERSEY-1978
    
    @Provider
    @PreMatching
    public class ContentTypeFilter implements ContainerRequestFilter {
    
        @Override
        public void filter(ContainerRequestContext requestContext) throws IOException {
            MultivaluedMap headers = requestContext.getHeaders();
            List contentTypes = headers.remove(HttpHeaders.CONTENT_TYPE);
            if (contentTypes != null && !contentTypes.isEmpty()) {
                String contentType = contentTypes.get(0);
                String sanitizedContentType = contentType.replaceFirst("; charset=UTF-8", "");
                headers.add(HttpHeaders.CONTENT_TYPE, sanitizedContentType);
            }
        }
    }
    

提交回复
热议问题