Akka Http 客户端类型不匹配

Akka Http client type mismatch

谁能告诉我为什么会出现以下错误?:

[error] HttpClient.scala:117: type mismatch;
[error]  found   : akka.stream.scaladsl.Sink[(akka.http.scaladsl.model.StatusCode, String),scala.concurrent.Future[(akka.http.scaladsl.model.StatusCode, String)]]
[error]  required: akka.stream.Graph[akka.stream.SinkShape[(akka.http.scaladsl.model.StatusCode, String)],scala.concurrent.Future[akka.http.scaladsl.model.StatusCode]]
[error]       source.via(flow).runWith(Sink.head)
[error]                                     ^

代码如下:

implicit def map2entity: ToEntityMarshaller[Map[String, Any]] = mapMarshaller(MediaTypes.`application/json`)

def mapMarshaller(mediaType: MediaType.WithFixedCharset): ToEntityMarshaller[Map[String, Any]] =
  Marshaller.withFixedContentType(mediaType) { m => HttpEntity(mediaType, JSONObject(m).toString()) }

def post(path: String, entity: Map[String, Any]): Future[StatusCode] = {
  val uri = Uri(getResourceUri(path))
  logger.info(s"httpPost: $uri")
  Marshal(entity).to[RequestEntity] flatMap { e =>
    val source = Source.single(HttpRequest(
      uri = uri.path.toString,
      method = HttpMethods.POST,
      entity = e))

    val flow = getConnection(uri.scheme)(uri.authority.host.address)
      .mapAsync(10) { r =>
        //(r.status -> Marshal(r.entity).to[String])
        Unmarshal(r.entity).to[String].flatMap(s => Future(r.status -> s))
      }

    source.via(flow).runWith(Sink.head)
  }
}

您的接收器 (Future[(StatusCode, String)]) 的物化值与您在函数 (Future[StatusCode]) 中声明的 return 类型不同。

如果你post函数只需要return状态码,你可以改这个调用

.flatMap(s => Future(r.status -> s))

对此

.map(_ => r.status)