paulj
paulj

Reputation: 337

rest calls not return correctly with curl

I have the following snippet(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() {...

When called with curl as follows:

They all return values for plainText.

However, adding the following:

  //above not working
  // This method is called if XML is request
  @GET
  @Produces(MediaType.APPLICATION_XML)
   public String xml2Output() {...

all curl commandline return xml2Output, regardless of content type, including text/plain

Do I need server configuration change? Curl command not correct?

Upvotes: 0

Views: 128

Answers (1)

cassiomolin
cassiomolin

Reputation: 130977

Use the Accept header for content negotation

HTTP has the concept of content negotation, that is, it allows us to provide different representations of a resource at the same URI. The user agents can specify which representation fit their capabilities the best. The Accept header is used in the request to indicate the media type that is acceptable by the client.

To address your issue, remove the Content-Type header (that indicates the media type of the payload) from the request and then add the Accept header to the request, indicating the media type that must be sent in the response.

Have a look at what the RFC 7231, the current reference for the HTTP protocol, says about these headers:

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. [...]

Matching JAX-RS annotations with HTTP headers

There a couple of things to keep in mind regarding how the JAX-RS runtime matches the HTTP headers with the annotation:

  • The value of the Accept header will be matched with the value of the @Produces annotation.
  • The value of the Content-Type header will be matched with the value of the @Consumes annotation.

For more details, check the Jersey documentation about resources.

In your situation, we have the following:

  • For @Produces(MediaType.APPLICATION_XML), use the Accept header with the value application/xml.

  • For @Produces(MediaType.TEXT_XML), use the Accept header with the value text/xml.

  • For @Produces(MediaType.TEXT_PLAIN), use the Accept header with the value text/plain.

Upvotes: 1

Related Questions