使用 Scala CLI,您可以在單一列中要求整個工具組
//> using toolkit latest
或者,您也可以只要求特定版本的 UPickle
//> using dep com.lihaoyi::upickle:3.1.0
在您的 build.sbt 檔案中,您可以新增對工具組的相依性
lazy val example = project.in(file("example"))
.settings(
scalaVersion := "3.2.2",
libraryDependencies += "org.scala-lang" %% "toolkit" % "0.1.7"
)
或者,您也可以只要求特定版本的 UPickle
libraryDependencies += "com.lihaoyi" %% "upickle" % "3.1.0"
在您的 build.sc 檔案中,您可以新增對 upickle 函式庫的相依性
object example extends ScalaModule {
def scalaVersion = "3.2.2"
def ivyDeps =
Agg(
ivy"org.scala-lang::toolkit:0.1.7"
)
}
或者,您也可以只要求特定版本的 UPickle
ivy"com.lihaoyi::upickle:3.1.0"
非同步請求
若要非同步傳送請求,可以使用 DefaultFutureBackend
import scala.concurrent.Future
import sttp.client4._
val asyncBackend = DefaultFutureBackend()
val response: Future[Response[String]] = quickRequest
.get(uri"https://example.com")
.send(asyncBackend)
import scala.concurrent.Future
import sttp.client4.*
val asyncBackend = DefaultFutureBackend()
val response: Future[Response[String]] = quickRequest
.get(uri"https://example.com")
.send(asyncBackend)
您可以在 sttp 文件 中深入了解基於 Future
的後端。
sttp 支援其他非同步包裝器,例如 Monix Task
、cats-effect Effect
、ZIO 的 ZIO
類型等等。您可以在 這裡 查看支援後端的完整清單。
WebSocket
您可以使用 DefaultFutureBackend
開啟 WebSocket,如下所示。
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import sttp.client4._
import sttp.ws.WebSocket
val asyncBackend = DefaultFutureBackend()
def useWebSocket(ws: WebSocket[Future]): Future[Unit] =
for {
_ <- ws.sendText("Hello")
text <- ws.receiveText()
} yield {
println(text)
}
val response = quickRequest
.get(uri"wss://ws.postman-echo.com/raw")
.response(asWebSocketAlways(useWebSocket))
.send(asyncBackend)
Await.result(response, Duration.Inf)
// prints: Hello
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import sttp.client4.*
import sttp.ws.WebSocket
val asyncBackend = DefaultFutureBackend()
def useWebSocket(ws: WebSocket[Future]): Future[Unit] =
for
_ <- ws.sendText("Hello")
text <- ws.receiveText()
yield
println(text)
val response = quickRequest
.get(uri"wss://ws.postman-echo.com/raw")
.response(asWebSocketAlways(useWebSocket))
.send(asyncBackend)
Await.result(response, Duration.Inf)
// prints: Hello
在 sttp 文件 中深入了解 WebSocket。
更多功能
您可以在 sttp 文件 中發現更多功能,例如串流、記錄、逾時等等。