https4s 如何对 REST 网络服务进行 POST 调用

https4s how to make a POST call to a REST web service

我正在尝试使用 http4s 库。我正在尝试使用一些 json 负载向 REST Web 服务发出 POST 请求。

当我阅读文档时 http://http4s.org/docs/0.15/ 我只能看到一个 GET 方法示例。

有谁知道如何制作 POST?

看起来示例中提到的 get/getAs 方法只是 fetch 方法的便利包装。参见 https://github.com/http4s/http4s/blob/a4b52b042338ab35d89d260e0bcb39ccec1f1947/client/src/main/scala/org/http4s/client/Client.scala#L116

使用 Request 构造函数并将 Method.POST 作为 method 传递。

fetch(Request(Method.POST, uri))
import org.http4s.circe._
import org.http4s.dsl._
import io.circe.generic.auto._      

case class Name(name: String)

  implicit val nameDecoder: EntityDecoder[Name] = jsonOf[Name]

  def routes: PartialFunction[Request, Task[Response]] = {
     case req @ POST -> Root / "hello" =>
     req.decode[Name] { name =>
     Ok(s"Hello, ${name.name}")
  }

希望对您有所帮助。

https4s 版本:0.14.11

困难的部分是如何设置 post 正文。当您深入研究代码时,您可能会发现 type EntityBody = Process[Task, ByteVector]。但这是什么鬼?但是,如果您还没有准备好深入研究 scalaz,只需使用 withBody.

object Client extends App {
  val client = PooledHttp1Client()
  val httpize = Uri.uri("http://httpize.herokuapp.com")

  def post() = {
    val req = Request(method = Method.POST, uri = httpize / "post").withBody("hello")
    val task = client.expect[String](req)
    val x = task.unsafePerformSync
    println(x)
  }

  post()
  client.shutdownNow()
}

P.S。我对 http4s 客户端的帮助post(跳过中文,阅读 scala 代码):http://sadhen.com/blog/2016/11/27/http4s-client-intro.html