【问题标题】:Sending JSON request with Spray IO Client使用 Spray IO 客户端发送 JSON 请求
【发布时间】:2015-11-21 18:24:39
【问题描述】:

现在我正在 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..

有什么想法吗?将不胜感激:)

【问题讨论】:

    标签: json scala io spray


    【解决方案1】:

    您应该使用正确的 ContentType 创建 HttpEntity:

    Post(url, HttpEntity(ContentTypes.`application/json`, message))
    

    这件事在文档http://spray.io/documentation/1.2.3/spray-http/#content-type-header中有解释

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 2015-04-26
      • 1970-01-01
      相关资源
      最近更新 更多