Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set content type?

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?

like image 329
mmdc Avatar asked May 30 '16 21:05

mmdc


People also ask

What is set Content-Type?

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 .

How do I specify Content-Type in Curl?

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.


1 Answers

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)))
like image 105
flavian Avatar answered Sep 28 '22 08:09

flavian