【发布时间】:2024-01-16 22:33:01
【问题描述】:
我有一个 JAX-RS REST 资源,它应该能够按照客户通过 Accept-Charset 标头的偏好所指示的不同字符集进行响应。
然而,由于 JAX-RS 似乎默认忽略 Accept-Charset 标头,我编写了两个方法明确说明我想要支持的两个不同字符集:
@GET
@Path("test")
@Produces("text/plain; charset=UTF-8")
public String test_utf8() {
return "Hello World";
}
@GET
@Path("test")
@Produces("text/plain; charset=cp1047")
public String test_cp1047() {
return "Hello World";
}
但是,现在使用 curl 调用该方法时:
curl -v -H "Accept-Charset: cp1047;q=1.0, *;q=0" "http://localhost:8080/rest/test" -H "Accept: text/plain"
服务器以 UTF-8 响应:
> GET /rest/test HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.50.3
> Accept-Charset: cp1047;q=1.0, *;q=0
> Accept: text/plain
>
< HTTP/1.1 200 OK
< Connection: keep-alive
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 19
< Date: Mon, 06 Jul 2020 21:29:11 GMT
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
Hello World
另外,服务器日志中会出现一条日志消息:
23:29:11,356 WARN [org.jboss.resteasy.resteasy_jaxrs.i18n](默认 任务2)RESTEASY002142:多个资源方法匹配请求“GET /test"。选择一个。匹配方法:[public java.lang.String org.example.RestResource.test_utf8(), public java.lang.String org.example.RestResource.test_cp1047()]
如何强制服务器接受客户端请求的字符集?
【问题讨论】:
-
您只能使用一种 REST 方法,而不是使用两种。在方法的正文中,您可以根据您的业务逻辑或请求动态设置响应字符集:
return Response.status(Response.Status.OK).entity(...).header("charset=UTF-8").build()
标签: java jax-rs wildfly resteasy