HTTP4S客户端。如何获得确切的请求和响应正文

时间:2017-01-26 21:04:20

标签: scala http4s

我正在写一个小的http4s客户端

val client = SimpleHttp1Client()
val uri = Uri.fromString(requestUrl).valueOr(throw _)
val task = POST(uri, UrlForm("username" -> userName, "password" -> password)).map{request => println("request: " + request.body)}

try {
   val response = client.expect[String](task).unsafePerformSync
   println("token: " + response)
   response
} catch {
   case e: Exception => println(e.getMessage);"BadToken"
}

输出就像

[info] Running com.researchnow.nova.shield.NovaShieldSetup 
[info] Emit(Vector(ByteVector(44 bytes, 0x757365726e616d653d616268737269766173746176612670617373776f72643d41726)))
[info] Failed: unexpected HTTP status: 400 Bad Request
[info] token: BadToken

如何将二进制请求体转换为String?我希望以明文形式看到正文和标题。

1 个答案:

答案 0 :(得分:1)

我和http4s团队在gitter上进行了对话并找到了回应。由于谷歌没有回复gitter talk,我在这里回答

val loggedReq = req.copy(body = request.body.observe(scalaz.stream.io.stdOutBytes))
println(loggedReq)

这会打印所有标题。如果我们使用loggedReq执行某些操作,那么我们将获得已发布的整个正文

loggedReq.as[String].run