在netty客户机中从httpresponse获取正文字节

ut6juiuv  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(395)

我正在尝试使用netty创建http客户机,一切正常,但是我很难解析主体。我的管道如下所示:

pipeline.addLast(new HttpClientCodec())
      pipeline.addLast(new HttpContentDecompressor())
      pipeline.addLast(new HttpObjectAggregator(1024*10))
      pipeline.addLast(new HttpClientHandler[A](key, metrics))

和客户端处理程序(用scala编写)

class HttpClientHandler[A: BodyParser](key: AttributeKey[Callback[A]], metrics: Metrics)
    extends SimpleChannelInboundHandler[FullHttpResponse]
    with LazyLogging {

  override def channelRead0(ctx: ChannelHandlerContext, msg: FullHttpResponse): Unit = {
    val callback = ctx.channel().attr(key).get()
    if (callback != null) {
      val response = buildResponse(msg)
      callback(response)
    } else {
      throw new Exception("Callback not present in channel context ... this is a bug")
    }
  }

  private def buildResponse(msg: FullHttpResponse): Either[Throwable, Response[A]] = {
    val result = {
      try {
        val parsedBody = BodyParser[A].parse(msg.content().asReadOnly())
        if (msg.status() == HttpResponseStatus.OK) {
          Right(Response.Ok(parsedBody))
        } else {
          Right(Response.Other(msg.status().code(), parsedBody))
        }
      } catch {
        case e: Throwable =>
          Left(e)
      }
    }
    result.fold(metrics.bodyParseFailure, metrics.successfulResponse)
    result
  }

  override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable): Unit = {
    logger.warn(s"error observed for channel ${ctx.channel()}, closing", cause)
    ctx.channel().attr(key).get().apply(Left(cause))
  }

}

主要问题是 msg.content() 也包含http数据(方法,版本,头…),但我只对正文感兴趣。我做错什么了?谢谢!

mitkmikd

mitkmikd1#

太奇怪了。。。 msg.content() 是一个 ByteBuf 只应包含请求/响应的有效负载。

qxgroojn

qxgroojn2#

结果表明,这是通过对echo服务器进行测试造成的,echo服务器会重复整个http请求,如下所示:

$ curl -X POST localhost:3000/a/b/c -v

* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 3000 (#0)

> POST /a/b/c HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.64.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Sat, 19 Dec 2020 09:50:56 GMT
< X-Http-Echo-Server-Id: 9fcf5d57-2ac7-4a92-8aed-775879bf3ac2
< Content-Type: text/plain;charset=utf-8
< Transfer-Encoding: chunked
< Server: Jetty(9.4.24.v20191120)
<
POST /a/b/c HTTP/1.1
Accept: */*
User-Agent: curl/7.64.1
Host: localhost:3000

* Connection #0 to host localhost left intact
* Closing connection 0

相关问题