6
votes

I use akka http client 2.4.6 to post a json to server (server requires message's content type to be applicaton/json to handle):

val request = HttpRequest(uri = "http://localhost:9000/auth/add-user",
        method = HttpMethods.POST,
        entity = ByteString(write(createUser)))
        .withHeaders(headers.`Content-Type`(ContentTypes.`application/json`))
      Http().singleRequest(request)

And I receive this warning:

Explicitly set HTTP header 'Content-Type: application/json' is ignored, explicit Content-Type header is not allowed. Set HttpRequest.entity.contentType instead.

and error on server side is:

415 Unsupported Media Type

How do I properly set content type for it?

1

1 Answers

9
votes

You need to use the predefined set of available ContentType definitions or make your own, and then pass that in when you set the data, but it has to be done through the withEntity method.

    // Making your own, from a string
    val c1 = ContentType(
     MediaType.custom(
      "my_custom_type",
      new MediaType.Encoding.Fixed(HttpCharsets.`UTF-8`))
    )

And then you pass this in to the request builder:

val req = HttpRequest(method = HttpMethods.POST, uri = Uri(url)
      .withQuery(..)
      .withHeaders(..)
      // notice how JSON content type is passed in here.
      .withEntity(ContentTypes.`application/json`, ByteString(write(createUser)))