gpt4 book ai didi

json - 如何设置内容类型?

转载 作者:行者123 更新时间:2023-12-02 10:52:29 24 4
gpt4 key购买 nike

我使用akka http客户端2.4.6将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)))

关于json - 如何设置内容类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37533907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com