Scala 将json正文添加到http4s请求

Scala 将json正文添加到http4s请求,scala,http4s,http4s-circe,Scala,Http4s,Http4s Circe,此tut显示了如何创建http4s请求: 我想将此请求更改为POST方法,并使用circe添加一个文本json正文。我尝试了以下代码: val body = json"""{"hello":"world"}""" val req = Request[IO](method = Method.POST, uri = Uri.uri("/"), body = body) 这给了我一个类型不匹配错误: [error] found : io.circe.Json [error] required

此tut显示了如何创建http4s请求:

我想将此请求更改为POST方法,并使用circe添加一个文本json正文。我尝试了以下代码:

val body = json"""{"hello":"world"}"""
val req = Request[IO](method = Method.POST, uri = Uri.uri("/"), body = body)
这给了我一个类型不匹配错误:

[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
我理解这个错误,但我不知道如何将
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()
说明:

请求类上的参数
body
的类型为
EntityBody[IO]
,它是
流[IO,Byte]
的别名。您不能直接将字符串或Json对象分配给它,您需要使用
withBody
方法

withBody
采用隐式
EntityEncoder
实例,因此您关于不想使用
EntityEncoder
的评论没有意义-如果您不想自己创建字节流,您必须使用一个。但是,http4s库为许多类型提供了预定义的库,而用于类型
Json
的库位于
org.http4s.circe.\u
。因此,进口声明

最后,您需要在此处调用
.unsafeRunSync()
以拉出
请求
对象,因为
withBody
返回一个
IO[Request[IO]]
。当然,更好的处理方法是将结果与其他
IO
操作链接起来。

从http4s20.0开始,用新的主体覆盖现有主体(默认为空)。仍然需要
EntityEncoder
,可以通过导入
org.http4s.circe来找到它。\u

import org.http4s.circe_
val body=json”“{“你好”:“世界”}”
val req=请求[IO](
method=method.POST,
uri=uri.uri(“/”)
)
.withEntity(机构)

我想这正是本文所涉及的内容:该页面展示了如何使用
EntityEncoder
s创建
cats.effect.IO[org.http4s.Entity[cats.effect.IO]
类型。我编辑了我的问题,以明确我不是不想使用EntityEncoder,而是它没有提供所需的类型。