如何设置内容类型?

How to set content type?

我使用 akka http 客户端 2.4.6 来 post 一个 json 到服务器(服务器要求消息的内容类型是 applicaton/json 来处理):

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)

我收到了这个警告:

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

服务器端的错误是:

415 Unsupported Media Type

如何正确设置它的内容类型?

您需要使用预定义的一组可用 ContentType 定义或自己制作,然后在设置数据时将其传入,但必须通过 withEntity 方法完成.

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

然后将其传递给请求生成器:

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)))