gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:57:03 25 4
gpt4 key购买 nike

我有以下代码片段(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 specifyresponse media types that are acceptable. [...]

3.1.1.5. Content-Type

The Content-Type header field indicates the media type of theassociated representation: either the representation enclosed in themessage payload or the selected representation, as determined by themessage 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com