您可以在單一行中要求整個工具組
//> using toolkit latest
或者,您也可以只要求特定版本的 sttp
//> using dep com.softwaremill.sttp.client4::core:4.0.0-M1
在您的 build.sbt 檔案中,您可以新增對工具組的依賴項
lazy val example = project.in(file("example"))
.settings(
scalaVersion := "3.2.2",
libraryDependencies += "org.scala-lang" %% "toolkit" % "0.1.7"
)
或者,您也可以只要求特定版本的 sttp
libraryDependencies += "com.softwaremill.sttp.client4" %% "core" % "4.0.0-M1"
在您的 build.sc 檔案中,您可以新增對 Toolkit 的依賴關係
object example extends ScalaModule {
def scalaVersion = "3.2.2"
def ivyDeps =
Agg(
ivy"org.scala-lang::toolkit:0.1.7"
)
}
或者,您也可以只要求特定版本的 sttp
ivy"com.softwaremill.sttp.client4::core:4.0.0-M1"
上傳檔案
若要上傳檔案,您可以在請求的內文中放入 Java Path
。
您可以使用 Paths.get("path/to/file")
直接取得 Path
,或使用 toNIO
將 OS-Lib 路徑轉換為 Java 路徑。
import sttp.client4.quick._
val file: java.nio.file.Path = (os.pwd / "image.png").toNIO
val response = quickRequest.post(uri"https://example.com/").body(file).send()
println(response.code)
// prints: 200
import sttp.client4.quick.*
val file: java.nio.file.Path = (os.pwd / "image.png").toNIO
val response = quickRequest.post(uri"https://example.com/").body(file).send()
println(response.code)
// prints: 200
多部分請求
如果 Web 伺服器可以一次接收多個檔案,您可以使用多部分內文,如下所示
import sttp.client4.quick._
val file1 = (os.pwd / "avatar1.png").toNIO
val file2 = (os.pwd / "avatar2.png").toNIO
val response = quickRequest
.post(uri"https://example.com/")
.multipartBody(
multipartFile("avatar1.png", file1),
multipartFile("avatar2.png", file2)
)
.send()
import sttp.client4.quick.*
val file1 = (os.pwd / "avatar1.png").toNIO
val file2 = (os.pwd / "avatar2.png").toNIO
val response = quickRequest
.post(uri"https://example.com/")
.multipartBody(
multipartFile("avatar1.png", file1),
multipartFile("avatar2.png", file2)
)
.send()
在 sttp 文件 中深入了解多部分請求。