7

My goal is to render an HTTP response in a Grails 3.1 controller method that has

  • a given status code (mostly 204, but potentially others, like 200)
  • no Content-Type, or Content-Encoding headers (since there is no content, right?)

render(status: 204) adds an arbitrary Content-Type: application/json header.

Furthermore, this method (see grails.artefact.controller.support.ResponseRenderer.render()) in this case invokes HttpServletResponse.sendError(), though it is not an error. Why is that?

Currently we solve this by dealing with the response directly:

response.status = statusCode.value()
response.flushBuffer()

But this prevents us from using Grails interceptors after method for doing something before the response is sent. This is why we are looking for a different way, which does not change the HTTP response (like adding a Content-Type header).

jack_kerouac
  • 1,482
  • 2
  • 15
  • 30
  • Can't you pass `contentType: 'whatever/you-want'` to `render()` as well as the `status`? – tim_yates Sep 26 '17 at 09:04
  • The `render` method ignores the `contentType` property, if no body is passed (e.g. through the `text` property). – jack_kerouac Sep 26 '17 at 11:06
  • I know this is old but for anyone that has an issue regarding the "The render method ignores the contentType property," from above, the trick is to add an empty `text: ''` in the params passed in the render method. Example: `render(contentType: "application/json", text: '', status: HttpStatus.ACCEPTED)`. This way the contetType will be taken into account. – nik686 Jul 21 '21 at 09:16

1 Answers1

-3

You can write just like:

response.status = 204
render ""

This will respond with Content-Type header as text/html;charset=utf-8. To change the content-type you can make use of Content negotiation in Grails.

To remove the Content-Type header completely, you can try response.setHeader("Content-Type", "")

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121