java - 休息调用不能正确返回与 curl

标签 java jersey

我有以下代码片段(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 :

5.3.2. Accept

The Accept header field can be used by user agents to specify response media types that are acceptable. [...]

3.1.1.5. Content-Type

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 与注释相匹配,需要记住以下几点:

有关更多详细信息,请查看Jersey documentation about resources .

根据您的情况,我们有以下情况:

  • 对于 @Produces(MediaType.APPLICATION_XML),请使用带有值 application/xmlAccept header 。

  • 对于 @Produces(MediaType.TEXT_XML),请使用带有值 text/xmlAccept header 。

  • 对于 @Produces(MediaType.TEXT_PLAIN),请使用带有值 text/plainAccept header 。

关于java - 休息调用不能正确返回与 curl ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41984088/

相关文章:

java - 当 SeekBar 传递值时更改 TextView 颜色

java - com.sun.jersey.api.view.Viewable无法解析,它是从required.class间接引用的

java - Google AppEngine URL 查询字符串参数未传递给 Jersey GET 处理程序

jakarta-ee - com.sun.jersey.server.impl.application.WebApplicationImpl _handleRequest

java - 找出 System.out.printf 将打印出多少字符(通常)的简单方法

java - 向导不重绘/重新验证 jframe

java - 简单的 Mahout 分类示例

java - 如何检查某些事件中经过了多少毫秒(java)

java - 无法访问 Spring Boot 和 Jersey 应用程序中的某些 Controller

java - Jackson 的 readEntity 正在将我的异常序列化为 java.lang.Throwable 而不是正确的错误异常