使用 Spray IO Client 发送 JSON 请求
Sending JSON request with Spray IO Client
现在我正在 Scala 中构建一个小型 API,它使用 Spray.IO 框架来处理请求和响应。
当我的 /update URL 被调用时,我想调用另一个 API 来处理实际的更新,连同这个请求我想添加一些 JSON 数据。
为此,我使用以下代码:
val message: String = "{\"elements\":[{\"id\":\"2\",\"attributes\":[{\"name\":\"value\",\"type\":\"float\",\"value\":\"46\"}]}],\"updateAction\":\"UPDATE\"}"
val url: String = "http://[domain]/update"
val pipeline: HttpRequest => Future[HttpResponse] = sendReceive
val response: Future[HttpResponse] = pipeline(
Post(url, message)
~> addHeaders(List(
RawHeader("Content-Type", "application/json")
))
)
response onComplete { completedResponse =>
println("Response: "+completedResponse.get.message.entity.asString)
}
但是当我检查日志时,我可以看到 Content-Type 实际上设置为 text/plain; charset=UTF-8
,这是因为 Spray IO Client 实际上决定了 Content-Type 本身。
所以我的问题是;我怎样才能让 Spray IO 真正将我的消息识别为 Content-Type:application/json
..
有什么想法吗?将不胜感激:)
您应该使用适当的 ContentType 创建 HttpEntity:
Post(url, HttpEntity(ContentTypes.`application/json`, message))
这件事在文档中有解释http://spray.io/documentation/1.2.3/spray-http/#content-type-header
现在我正在 Scala 中构建一个小型 API,它使用 Spray.IO 框架来处理请求和响应。
当我的 /update URL 被调用时,我想调用另一个 API 来处理实际的更新,连同这个请求我想添加一些 JSON 数据。
为此,我使用以下代码:
val message: String = "{\"elements\":[{\"id\":\"2\",\"attributes\":[{\"name\":\"value\",\"type\":\"float\",\"value\":\"46\"}]}],\"updateAction\":\"UPDATE\"}"
val url: String = "http://[domain]/update"
val pipeline: HttpRequest => Future[HttpResponse] = sendReceive
val response: Future[HttpResponse] = pipeline(
Post(url, message)
~> addHeaders(List(
RawHeader("Content-Type", "application/json")
))
)
response onComplete { completedResponse =>
println("Response: "+completedResponse.get.message.entity.asString)
}
但是当我检查日志时,我可以看到 Content-Type 实际上设置为 text/plain; charset=UTF-8
,这是因为 Spray IO Client 实际上决定了 Content-Type 本身。
所以我的问题是;我怎样才能让 Spray IO 真正将我的消息识别为 Content-Type:application/json
..
有什么想法吗?将不胜感激:)
您应该使用适当的 ContentType 创建 HttpEntity:
Post(url, HttpEntity(ContentTypes.`application/json`, message))
这件事在文档中有解释http://spray.io/documentation/1.2.3/spray-http/#content-type-header