gpt4 book ai didi

json - 在spray中发送post请求

转载 作者:行者123 更新时间:2023-12-04 06:04:29 25 4
gpt4 key购买 nike

我需要使用 spray 发出一个简单的 HTTP 请求框架。我在他们的网站上找到了一些示例,但结果证明它们很复杂并且涉及 Akka,这对我来说是不必要的。

此外,我需要能够填写请求的 header (如 X-Applicationcontent-type 等),当然还有请求的发布数据(在我的情况下,它将是 JSON 中的数据)。

那我该怎么做呢?

最佳答案

这是一个例子。会有少量的 akka 代码,但正如我在评论中提到的,spray 是必要的:

import spray.httpx.RequestBuilding._
import spray.http._
import HttpMethods._
import HttpHeaders._
import MediaTypes._
import spray.json._
import DefaultJsonProtocol._
import spray.httpx.SprayJsonSupport._
import akka.actor.ActorSystem
import spray.io.IOExtension
import akka.actor.Props
import spray.can.client.HttpClient
import spray.client.HttpConduit
import scala.concurrent.Future
import scala.util.Failure
import scala.util.Success

case class MyObj(str:String, i:Int)

object SprayExample {
implicit val myObjFormat = jsonFormat2(MyObj)

def main(args: Array[String]) {
import concurrent.ExecutionContext.Implicits._

val obj = MyObj("hello", 1)
val req = Post("/some/url", obj) ~> addHeader("X-Foo", "bar")

implicit val system = ActorSystem()
val ioBridge = IOExtension(system).ioBridge()
val httpClient = system.actorOf(Props(new HttpClient(ioBridge)))

val conduit = system.actorOf(
props = Props(new HttpConduit(httpClient, "localhost", 8080)),
name = "http-conduit"
)

val pipeline = HttpConduit.sendReceive(conduit)
val response: Future[HttpResponse] = pipeline(req)
response onComplete{
case Failure(ex) => ex.printStackTrace()
case Success(resp) => println("success: " + resp.status)
}
}
}

我的构建文件如下所示:
scalaVersion := "2.10.0"

resolvers ++= Seq(
"Scala Tools Repo Releases" at "http://scala-tools.org/repo-releases",
"Typesafe Repo Releases" at "http://repo.typesafe.com/typesafe/releases/",
"spray" at "http://repo.spray.io/"
)


libraryDependencies ++= Seq(
"io.spray" % "spray-httpx" % "1.1-M7",
"io.spray" % "spray-client" % "1.1-M7",
"com.typesafe.akka" %% "akka-actor" % "2.1.0",
"io.spray" %% "spray-json" % "1.2.5"
)

关于json - 在spray中发送post请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17008878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com