当 Content-Type
header 中指定了 charset
属性时,Jersey 2.0(使用 servlet 3.1)似乎无法解码参数。
例如考虑以下端点:
@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 请求有效:
curl -X POST -H "content-type: application/x-www-form-urlencoded" -d "name=tom" http://localhost:8080/sampleapp/hello
以下请求不起作用并且name
参数为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
破坏了我的代码。
编辑:
我已经打开了一张官方票以防这是一个错误:https://java.net/jira/browse/JERSEY-1978
最佳答案
我认为这是一个错误。
有一个打开的请求请求来支持这个用例: https://github.com/jersey/jersey/pull/24/files
与此同时,我建议使用过滤器来删除有问题的编码。
EDIT 根据 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);
}
}
}
关于java - 当在 Content-Type 中指定字符集时,Jersey 和 @FormParam 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17602432/