【问题标题】:Akka Http client type mismatchAkka Http 客户端类型不匹配
【发布时间】:2018-02-16 13:28:49
【问题描述】:

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

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

【问题讨论】:

    标签: scala akka-http


    【解决方案1】:

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

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

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

    到这里

    .map(_ => r.status)
    

    【讨论】:

    • 忘记更改返回类型 :P ...所以我更改了函数Future[(StatusCode, String)] 的返回类型。好几天了
    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 2014-01-08
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多