akka http - 如何将json数据添加到发布请求中?

时间:2017-03-16 20:00:07

标签: akka akka-http

我正在查询搜索API,我需要在json中添加查询参数作为发布请求的正文。

val headers: scala.collection.immutable.Seq[HttpHeader] = scala.collection.immutable.Seq(
  RawHeader("accept", "application/json"),
  RawHeader("authorization", "xxxxxxxxxxxxxxxxxxxx"),
  RawHeader("content-type", "application/json"),
  RawHeader("x-customer-id", "123456789")
)

val formData = FormData(Map(
      "Keywords" -> "query", "Count" -> "25"
    ))

val request = HttpRequest(HttpMethods.POST, "https://api.xxx.com/services/xxx/v1/search?client_id=xxxxxx", headers, formData.toEntity)

使用formData.toEntity会将其作为json发送到帖子的正文中吗?

1 个答案:

答案 0 :(得分:0)

我为搜索查询创建了一个类并将其序列化并创建了HttpEntity,如下所示:

case class SearchObject(keyWords: String, count: Int)

val reqHeaders: scala.collection.immutable.Seq[HttpHeader] = scala.collection.immutable.Seq(
  RawHeader("accept", "application/json"),
  RawHeader("authorization", "xxxxxxxxxxxxxxxxxxxx"),
  RawHeader("content-type", "application/json"),
  RawHeader("x-customer-id", "123456789")
)

val searchObject = net.liftweb.json.Serialization.write(req) //req is search object
val searchObjectEntity = HttpEntity(ContentTypes.`application/json`, searchObject)
val request = HttpRequest(HttpMethods.POST, "https://api.xxxxxxxx.com/services/xxxxxx/v1/search?client_id=45854689", reqHeaders, searchObjectEntity)