【问题标题】:REST Api -API response doesn't have a consistent default content type in headerREST Api -API 响应在标头中没有一致的默认内容类型
【发布时间】:2017-06-28 11:38:32
【问题描述】:

当我使用下面的 URL 和代码从 rest-easy 发出请求时。我得到每个请求的不同响应(调用 API 而不在请求标头中指定内容类型。多次执行此操作以查看不同的结果)。我正在使用rest-easy(Firefox插件)来调用URL并获得响应

我希望默认情况下以“text/plain”的形式获得响应。还有其他格式,如 java/x-java-properties、text/xml。
如果我没有在请求标头中指定 Accept 参数,我想获得 text/plain 响应。现在我有时会得到 text/plain,有时会得到 text/x-java-properties 或 text/xml

已部署的版本在我的本地系统中。我可以通过调用以下 URL 获得响应:

网址:http://localhost:8081/restfuljersey/rest/hello

代码:

import javax.ws.rs.GET; 
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/hello")
public class Hello {
  @GET
  @Produces("text/plain")
  public String sayPlainTextHello() {
    return "Hello Jersey Plain";
  }
  @GET
  @Produces("text/x-java-properties")
  public String sayHtmlHelloProperties( ) {
          return "Hello Jersey Plain1111";
  }
  // This method is called if XML is request
  @GET
  @Produces("text/xml")
  public String sayXMLHello() {
    return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
  }
  // This method is called if HTML is request
  @GET
  @Produces("text/html")
  public String sayHtmlHello() {
    return "<html> " + "<title>" + "Hello Jersey" + "</title>"
        + "<body><h1>" + "Hello Jersey HTML" + "</h1></body>" + "</html> ";
  }
}

【问题讨论】:

  • 目前的反应是什么?你想达到什么目标?
  • 我希望默认情况下以“text/plain”获得响应。但是对于每个请求,我都会得到不同的响应,例如 text/plain 或 text/x-java-properties 或 text/xml。

标签: java web-services rest api


【解决方案1】:

除非您自己指定标头,否则所有浏览器都会在 HTTP 请求中为 Accept 标头使用一组默认值。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation/List_of_default_Accept_values

例如火狐使用Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

在这些值中,您可以找到通配符标头*/*,它允许服务器选择它返回的内容类型。浏览器使用它来涵盖所有可能的情况。

【讨论】:

  • 如果是/*/*,服务器如何识别响应类型?要指定任何默认值吗?有什么需要做的配置吗?
  • @Seshadri 这取决于服务器的 JAX-RS 实现。您不能假设所有服务器在收到 Accept: */* 标头时都返回相同的内容类型,例如Jersey 框架可以返回与 RESTEasy 框架完全不同的内容类型。我不知道配置此行为的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-02
  • 2019-02-24
  • 1970-01-01
相关资源
最近更新 更多