繁体   English   中英

如何使用 akka-http 将字节流解析为 `HttpRequest` 对象?

[英]How to parse a byte stream into `HttpRequest` objects with akka-http?

文档中:“目前没有提供公共 API 来解析(或呈现到)字符串或字节数组”。 如何使用私有 API 将网络流解析为HttpRequest对象?

另外,输入字节流应该是什么?

  1. 无序数据包(以太网及以上)
  2. 无序的 tcp 数据包
  3. 有序的 tcp 有效载荷(http 原始请求,按顺序)(这是​​我的猜测)

笔记:

  1. 我的字节流将只包含 http 请求,不包含响应
  2. 我从 pcap 文件中获取此字节流,而不是从实时 http 客户端获取。 (这也是为什么我要问在发送到akka-http之前我需要解析多少)
  3. 如果您认为这是一个坏主意,请解释一下,这也会有很大帮助。
  4. 我怀疑这涉及使用 http().serverLayer。 我不确定。

链接:Akka Google Group 中的一个相关问题

谢谢!

这是可能的,但是很奇怪。 我已经做到了,但是由于私有的,所以我无法在此处发布完整的代码。

与此相关的AKKA代码位于HttpRequestParser

大部分代码都是私有程序包,因此您需要在akka.http程序包中编写自己的帮助程序类才能访问它。

该代码将如下所示:

package akka.http

/**
 * This class gives us access to Akka's [[akka.http.impl.engine.parsing.HttpRequestParser]].
 *
 * It is in the akka package, as most of Akka's parsing code is package-private.
 *
 * @see [[akka.http.impl.engine.server.HttpServerBluePrint]]
 */    
class HttpRequestParserHelper()(
    implicit system: ActorSystem,
    materializer: Materializer) {

  def unmarshalRequest(wireFormat: Array[Byte]): HttpRequest = {

    val input = ByteString(wireFormat)

    val requestFuture = Source.single(input)
      .via(requestParsingFlow())
      .runWith(Streams.getSingleElement)
      .transform(identity, e =>
        new IOException("Error unmarshalling request", e))

    Await.result(requestFuture, 10.seconds)
  }

  /**
   * An Akka Flow which parses incoming ByteStrings and emits HttpRequests.
   *
   * This code was copied from [[akka.http.impl.engine.server.HttpServerBluePrint]]
   */
  private def requestParsingFlow(): Flow[ByteString, HttpRequest, Any] = {
    ... 
  }
}

从AKKA源代码中填写requestParsingFlow ,删除直到编译时才适用的位。

输入数据必须是TCP流数据,即问题中的选项(3)。

祝好运!

一种方法是执行以下操作

在你的项目中包含libraryDependencies += "com.athaydes.rawhttp" % "rawhttp-core" % "2.4.1"

然后将byteString解析为RawHttpRequest 然而,这不是常规的 akka HttpRequest但可以从RawHttpRequest创建HttpRequest

    case Received(data) =>
      val decoded = data.utf8String
      val rawHttp = new RawHttp
      val rawHttpRequest = rawHttp.parseRequest(data.utf8String)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM