2017-03-16 91 views
3

我正在查詢一個搜索api,我需要將json中的查詢參數添加到發佈請求中。akka http - 如何將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在帖子的主體?

+0

你需要一個「編組」像傑克遜或json4s ... –

回答

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)