如何设置内容类型?

问题描述 投票:3回答:1

我使用akka http客户端2.4.6将json发布到服务器(服务器要求消息的内容类型为应用程序/ 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)

我收到这个警告:

显式设置HTTP标头'Content-Type:application / json'被忽略,不允许显式的Content-Type标头。改为设置HttpRequest.entity.contentType

服务器端的错误是:

415不支持的媒体类型

如何正确设置内容类型?

json scala akka-http
1个回答
6
投票

您需要使用预定义的可用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)))
© www.soinside.com 2019 - 2024. All rights reserved.