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

时间:2016-07-28 18:43:02

标签: scala http4s

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

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

有谁知道如何发布POST?

3 个答案:

答案 0 :(得分:1)

示例中提到的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))

答案 1 :(得分:1)

https4s版本:0.14.11

困难的部分是如何设置帖体。当您深入研究代码时,您可能会发现type EntityBody = Process[Task, ByteVector]。但wtf是吗?但是,如果您还没有准备好潜入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客户端的有用帖子(只需跳过中文并阅读scala代码):http://sadhen.com/blog/2016/11/27/http4s-client-intro.html

答案 2 :(得分:-3)

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}")
  }

希望这有帮助。