在Content-Type中指定charset时,Jersey和@FormParam无法正常工作

Mar*_*ark 9 java servlets jax-rs jersey http-headers

看起来Jersey 2.0(使用servlet 3.1)charsetContent-Type标题中指定属性时无法解码参数.

例如,考虑以下端点:

@POST
@Path("/hello")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response hello(@FormParam("name") String name) {
    System.out.println(name);
    return ok();
}
Run Code Online (Sandbox Code Playgroud)

这个卷曲请求有效:

curl -X POST -H "content-type: application/x-www-form-urlencoded" -d "name=tom" http://localhost:8080/sampleapp/hello
Run Code Online (Sandbox Code Playgroud)

下面的请求,而不是工作,该name参数是null:

curl -X POST -H "content-type: application/x-www-form-urlencoded; charset=UTF-8" -d "name=tom" http://localhost:8080/sampleapp/hello
Run Code Online (Sandbox Code Playgroud)

我认为charset=UTF-8内容类型中的添加会破坏我的代码.

编辑:

我打开了官方机票以防这是一个错误:https://java.net/jira/browse/JERSEY-1978

Car*_*ini 7

我认为这是一个错误.

有一个pull请求可以支持这个用例:https: //github.com/jersey/jersey/pull/24/files

与此同时,我建议使用过滤器来删除有问题的编码.

根据OP评论编辑

我正在考虑这些方面的事情:

@Provider
@PreMatching
public class ContentTypeFilter implements ContainerRequestFilter{

    @Override
    public void filter(ContainerRequestContext requestContext)
            throws IOException {
        MultivaluedMap<String,String> headers=requestContext.getHeaders();
        List<String> contentTypes=headers.remove(HttpHeaders.CONTENT_TYPE);
        if (contentTypes!=null && !contentTypes.isEmpty()){
            String contentType= contentTypes.get(0);
            String sanitizedContentType=contentType.replaceFirst(";.*", "");
            headers.add(HttpHeaders.CONTENT_TYPE, sanitizedContentType);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)