Scala 将json正文添加到http4s请求
此tut显示了如何创建http4s请求: 我想将此请求更改为POST方法,并使用circe添加一个文本json正文。我尝试了以下代码: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
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,而是它没有提供所需的类型。