抱歉,我无法完成这项工作:我需要在帖子中添加一些json,因此请遵循文档:http://spray.io/documentation/1.1-M8/spray-httpx/request-building/:
import scala.util.{Success, Failure}
import akka.actor.{Props, ActorSystem}
import spray.can.client.DefaultHttpClient
import spray.client.HttpConduit
import spray.httpx.SprayJsonSupport
import spray.http._
import spray.json.JsonParser._
import spray.json._
import HttpMethods._
import HttpHeaders._
import MediaTypes._
import spray.httpx.RequestBuilding._
import scala.concurrent.ExecutionContext.Implicits.global
...
val req = HttpRequest(method = POST, uri = "/api/1.0/users/ping.json", entity = HttpEntity(`application/json`,"""{ "key"="whatever" }"""))
它永远不会编译:
overloaded method value apply with alternatives:
[error] (optionalBody: Option[spray.http.HttpBody])spray.http.HttpEntity <and>
[error] (buffer: Array[Byte])spray.http.HttpEntity <and>
[error] (string: String)spray.http.HttpEntity
[error] cannot be applied to (spray.http.MediaType, String)
[error] val req = HttpRequest(method = POST, uri = "/api/1.0/users/ping.json", entity = HttpEntity(`application/json`,"""{ "key"="whatever"}"""))
答案 0 :(得分:4)
遇到同样的问题并在此处找到解决方案:
这最终对我有用:
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))
}
答案 1 :(得分:0)
很抱歉,但至少对我来说,你的问题有点麻烦。如果你想在Spray中使用一些Json作为HttpEntity发出POST请求,那么你应该尝试使用Spray-Clients流水线操作,这很简单。
您需要创建一个简单的管道:
val pipe: HttpRequest => Future[HttpResponse] = sendReceive
然后构建一个请求:
import spray.json.SprayJsonSupport._
pipe(Post("/api/1.0/users/ping", """{ "key"="whatever" }""".asJson))
这会返回Future
HttpResponse
val pipe: HttpRequest => Future[ConfCode] = sendReceive ~> unmarshal[ConfCode]
,如果你想要一些特定的结果,比方说一些确认代码,然后在你的管道中添加unmarshall步骤:
{{1}}
答案 2 :(得分:0)
这也是我尝试过的,但它不起作用它告诉我,我错过了隐含的内容:
val pipeline = sendReceive(conduit)
val responseF = pipeline(Post("/api/1.0/users/ping.json", """{ "key": "whatever" }""".asJson))
responseF onComplete { ...
但我总是得到:
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))
您之前快照中的导入也不起作用....我使用的是该库的错误版本吗?我的设置是:
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,