Sending post with json using spray?

戏子无情 提交于 2019-12-04 13:04:29

Had the same problem and found the solution here:

https://github.com/spray/spray-json/blob/master/src/main/scala/spray/json/AdditionalFormats.scala#L30-41

This finally worked for me:

import spray.httpx.SprayJsonSupport
import spray.json.AdditionalFormats

object Client extends SprayJsonSupport with AdditionalFormats {
    val email = "..."
    val password = "..."
    val pipeline = sendReceive       
    pipeline(Post("http://something.com/login", s"""{
        "email": "$email",
        "password": "$password"
    }""".asJson.asJsObject))
}

Sorry, but you question is a bit cumbersome, for me at least. If you want to make a POST request in Spray with some Json as HttpEntity, then you should try to do it with Spray-Clients pipelining, it's drop dead simple.

You need to create a simple pipe:

val pipe: HttpRequest => Future[HttpResponse] = sendReceive

and then build a request:

import spray.json.SprayJsonSupport._
pipe(Post("/api/1.0/users/ping", """{ "key"="whatever" }""".asJson))

This will return you a Future with HttpResponse, if you want some specific result, let's say, for example, some confirmation code, then add unmarshall step to your pipe:

val pipe: HttpRequest => Future[ConfCode] = sendReceive ~> unmarshal[ConfCode]

That is what i tried too, but it doesn't work it is telling me that I am missing an implicit:

val pipeline = sendReceive(conduit)
val responseF = pipeline(Post("/api/1.0/users/ping.json", """{ "key": "whatever" }""".asJson))

responseF onComplete { ...

but i always get :

could not find implicit value for evidence parameter of type spray.httpx.marshalling.Marshaller[spray.json.JsValue]
[error]     val responseF = pipeline(Post("/api/1.0/users/ping.json", """{ "key": "whatever" }""".asJson))

also the import you have in your previous snapshot does not work.... Am i using a bad version of the library? My sbt settings are:

val sprayVersion = "1.1-M7"
val akkaVersion = "2.1.1"
"io.spray" %% "spray-json"   % "1.2.5",
    "com.typesafe.akka" %% "akka-actor" % akkaVersion,
    "com.typesafe.akka" %% "akka-slf4j" % akkaVersion,
    "io.spray" %  "spray-client" % sprayVersion,
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!