Her*_*III 4 scala http4s http4s-circe
这个tut展示了如何创建一个http4s请求:https://http4s.org/v0.18/dsl/#testing-the-service
我想将此请求更改为POST方法并使用circe添加文字json正文.我尝试了以下代码:
val body = json"""{"hello":"world"}"""
val req = Request[IO](method = Method.POST, uri = Uri.uri("/"), body = body)
Run Code Online (Sandbox Code Playgroud)
这给了我一个类型不匹配的错误:
[error] found : io.circe.Json
[error] required: org.http4s.EntityBody[cats.effect.IO]
[error] (which expands to) fs2.Stream[cats.effect.IO,Byte]
[error] val entity: EntityBody[IO] = body
Run Code Online (Sandbox Code Playgroud)
我理解错误,但我无法弄清楚如何转换io.circe.Json为EntityBody.我见过的大多数例子都使用了一个EntityEncoder,它没有提供所需的类型.
我怎样才能转换io.circe.Json成EntityBody?
Oleg的链接主要涵盖它,但这里是你如何为自定义请求体做到这一点:
import org.http4s.circe._
val body = json"""{"hello":"world"}"""
val req = Request[IO](method = Method.POST, uri = Uri.uri("/"))
.withBody(body)
.unsafeRunSync()
Run Code Online (Sandbox Code Playgroud)
说明:
body请求类上的参数的类型EntityBody[IO]是别名Stream[IO, Byte].您不能直接为其指定String或Json对象,而是需要使用该withBody方法.
withBody采用隐式EntityEncoder实例,因此您不想使用的注释没有EntityEncoder意义 - 如果您不想自己创建字节流,则必须使用它.但是,http4s库已为多种类型预定义了一个类型,而类型的库则Json存在org.http4s.circe._.因此导入声明.
最后,你需要在.unsafeRunSync()这里调用一个Request对象,因为withBody返回一个IO[Request[IO]].处理此问题的更好方法当然是通过将结果与其他IO操作联系起来.
从 http4s 20.0 开始,withEntity用新主体覆盖现有主体(默认为空)。将EntityEncoder仍然需要,并能与进口中找到org.http4s.circe._:
import org.http4s.circe._
val body = json"""{"hello":"world"}"""
val req = Request[IO](
method = Method.POST,
uri = Uri.uri("/")
)
.withEntity(body)
Run Code Online (Sandbox Code Playgroud)