如何设置内容类型?
问题描述:
我用阿卡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不支持的媒体类型
如何正确设置的内容类型呢?
答
您需要使用预定义的一组可用的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)))