21

I try to send an HTTP POST request to a service endpoint using Play2/Scala WS API. Since there is no parameters to be sent in the HTTP POST body, how can I send it using

WS.url("http://service/endpoint").post()

I have tried post() without argument but it gave me an error.

Cannot write an instance of Unit to HTTP response. Try to define a Writeable[Unit]

Can you please help on this ?

thanks in advance...

Ricardo
  • 3,696
  • 5
  • 36
  • 50
kaffein
  • 1,766
  • 2
  • 28
  • 54

3 Answers3

31

Since post awaits a value that implements the Writeable and ContentTypeOf type classes, you can use the Results.EmptyContent from play.api.mvc. (See API)

So I guess

WS.url("http://service/endpoint").post(Results.EmptyContent())

should do. (Didnt test)

Martin Ring
  • 5,404
  • 24
  • 47
31

For Play 2.6 and after, you have to use play.api.libs.ws.EmptyBody.

import play.api.libs.ws.{EmptyBody, WSClient}
WS.url("http://service/endpoint").post(EmptyBody)

Typical error is:

Cannot find an instance of play.api.mvc.Results.EmptyContent to WSBody. Define a BodyWritable[play.api.mvc.Results.EmptyContent] or extend play.api.libs.ws.ahc.DefaultBodyWritables
Ricardo
  • 3,696
  • 5
  • 36
  • 50
Thomas Pocreau
  • 470
  • 5
  • 12
  • What about the content type? – Rich Feb 26 '20 at 21:15
  • I still get "Cannot write an instance of play.api.libs.ws.WSBody to HTTP response. Try to define a Writeable[play.api.libs.ws.WSBody]". So I have to define a trivial `BodyWritable[WSBody]`? How do I represent no Content-Type header? c.f. https://stackoverflow.com/questions/29784398/should-content-type-header-be-present-when-the-message-body-is-empty – Rich Feb 26 '20 at 21:16
2

As of Play 2.8, you cannot use the WSRequest.post(body) methods with an empty body, because the BodyWritable trait requires a non-empty Content-Type

Instead, you can do ws.url(u).execute("POST") to send an HTTP POST request with no body.

Rich
  • 15,048
  • 2
  • 66
  • 119