我有以下代码片段(Jersey Rest 1.9 Tomcat 7):
import javax.ws.rs.GET;...
// This method is called if TEXT_PLAIN is request
@GET
@Produces(MediaType.TEXT_PLAIN)
public String plainTextOutput() {...
// This method is called if XML is request
@GET
@Produces(MediaType.TEXT_XML) ...
public String xmlOutput() {...
当使用curl 调用时,如下所示:
- curl 网址
- -H“内容类型:text/xml”
- -H“内容类型:application/xml
它们都返回纯文本值。
但是,添加以下内容:
//above not working
// This method is called if XML is request
@GET
@Produces(MediaType.APPLICATION_XML)
public String xml2Output() {...
所有curl命令行都返回xml2Output,无论内容类型如何,包括text/plain
我需要更改服务器配置吗? Curl 命令不正确?
最佳答案
使用Accept
header 进行内容协商
HTTP 具有内容协商的概念,也就是说,它允许我们在同一 URI 上提供资源的不同表示形式。用户代理可以指定哪种表示最适合他们的功能。 Accept
请求中使用 header 来指示客户端可接受的媒体类型。
要解决您的问题,请删除 Content-Type
请求中的 header (指示有效负载的媒体类型),然后添加 Accept
请求的 header ,指示必须在响应中发送的媒体类型。
看看RFC 7231是什么HTTP 协议(protocol)的当前引用,介绍了这些 header :
The
Accept
header field can be used by user agents to specify response media types that are acceptable. [...]
The
Content-Type
header field indicates the media type of the associated representation: either the representation enclosed in the message payload or the selected representation, as determined by the message semantics. [...]
将 JAX-RS 注释与 HTTP header 相匹配
关于 JAX-RS 运行时如何将 HTTP header 与注释相匹配,需要记住以下几点:
Accept
的值 header 将与@Produces
的值匹配注释。Content-Type
的值 header 将与@Consumes
的值匹配注释。
有关更多详细信息,请查看Jersey documentation about resources .
根据您的情况,我们有以下情况:
对于
@Produces(MediaType.APPLICATION_XML)
,请使用带有值application/xml
的Accept
header 。对于
@Produces(MediaType.TEXT_XML)
,请使用带有值text/xml
的Accept
header 。对于
@Produces(MediaType.TEXT_PLAIN)
,请使用带有值text/plain
的Accept
header 。
关于java - 休息调用不能正确返回与 curl ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41984088/