简体   繁体   中英

Akka Http client type mismatch

Can anyone tell me why I'm getting the following error?:

[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]                                     ^

Here's the code:

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)
  }
}

The materialized value of your sink ( Future[(StatusCode, String)] ) is different from the return type you declared in the function ( Future[StatusCode] ).

If you post function only needs to return the status code, you can change this call

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

To this

.map(_ => r.status)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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