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. SetHttpRequest.entity.contentType
instead.
and error on server side is:
415 Unsupported Media Type
How do I properly set content type for it?
setContentType. Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification, for example, text/html;charset=UTF-8 .
Setting the Content-Type of a Curl Request. To send the Content-Type header using Curl, you need to use the -H command-line option. For example, you can use the -H "Content-Type: application/json" command-line parameter for JSON data. Data is passed to Curl using the -d command-line option.
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With