3

抱歉,我无法完成这项工作:我需要在帖子中添加一些 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"}"""))
4

3 回答 3

4

遇到了同样的问题,在这里找到了解决方案:

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

这终于对我有用:

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))
}
于 2013-12-11T21:40:27.027 回答
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))

这将返回一个Futurewith HttpResponse,如果你想要一些特定的结果,比如说,一些确认码,然后将 unmarshall 步骤添加到你的管道中:

val pipe: HttpRequest => Future[ConfCode] = sendReceive ~> unmarshal[ConfCode]
于 2013-09-04T22:00:32.510 回答
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))

您在以前的快照中的导入也不起作用....我使用的是错误版本的库吗?我的 sbt 设置是:

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,
于 2013-09-05T12:59:06.900 回答