在Content-Type中指定charset时,Jersey和@FormParam无法正常工作 [英] Jersey and @FormParam not working when charset is specified in the Content-Type

查看:480
本文介绍了在Content-Type中指定charset时,Jersey和@FormParam无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Content-Type中指定 charset 属性时,似乎Jersey 2.0(使用servlet 3.1)无法解码参数 header。

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.

例如,考虑以下端点:

@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();
}

此卷曲请求有效:

curl -X POST -H "content-type: application/x-www-form-urlencoded" -d "name=tom" http://localhost:8080/sampleapp/hello

以下请求改为工作且 name 参数是 null

The following request instead doesn't work and the name parameter is null:

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

我认为 charset = UTF-8 加入内容类型打破了我的代码。

I think the charset=UTF-8 addition in the content type breaks my code.

编辑:

我已开通官方机票,以防万一是一个错误: https://java.net/jira/browse/JERSEY-1978

I've opened an official ticket just in case this is a bug: https://java.net/jira/browse/JERSEY-1978

推荐答案

我认为这是一个错误。

I think it's a bug.

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

There's a pull request open to support this use case: https://github.com/jersey/jersey/pull/24/files

在此期间我' d建议使用过滤器来删除有问题的编码。

In the meantime I'd suggest to use a filter to remove the offending encoding.

编辑根据OP评论

我正在考虑这些问题行:

I'm thinking on something along these lines:

@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);
        }
    }
}

这篇关于在Content-Type中指定charset时,Jersey和@FormParam无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆