Akka-Http客户端:如何从http响应中获取二进制数据?

时间:2017-09-08 19:33:03

标签: scala akka-http

我调用API来获取zip文件响应。 API响应正确,但我无法从响应中获取字节数组,因为在获取ByteString时应该完成的未来永远不会完成:

    val authorization =  akka.http.javadsl.model.headers.Authorization.basic("xxxxx", "xxxxxx")
    val query = Map("fed" -> "xxxx", "trd" -> "yyy", "id" -> "zzz")
    val request = HttpRequest(HttpMethods.GET, Uri("https://xxxx.yyyy.com/ggg/ttt.php").withQuery(Query(params = query))).addHeader(authorization)
    val responseFut = http.singleRequest(request)
    responseFut1.map(response => {
    println("*******************************")
    println(response)
    response.status match {
      case akka.http.javadsl.model.StatusCodes.OK => {
        println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" + response._3)
        val entityFut = response.entity.toStrict(60.seconds)
        val byteStringFut = entityFut.flatMap(entity => {
          entity.dataBytes.runFold(ByteString.empty)(_ ++ _)
        })
        println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
        try {
          byteStringFut.map(x => {
          //this never prints =======================================problem     
            println("----------------------------" + x.toArray[Byte])
          })
        }catch{
          case e: Exception => println("Error: " + e)
        }
      }
      case _ => {}
    }
  })

如果我打印出response这就是它的样子:

*******************************
HttpResponse(200 OK,List(Date: Fri, 08 Sep 2017 20:58:43 GMT, Server: Apache/2.4.18 (Ubuntu), Content-Disposition: attachment; filename="xxxxx.zip", Pragma: public, Cache-Contr
ol: public, must-revalidate, Content-Transfer-Encoding: binary),HttpEntity.Chunked(application/x-zip),HttpProtocol(HTTP/1.1))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^HttpEntity.Chunked(application/x-zip)
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

所以响应很好,但我仍然无法获得zip文件的二进制数据。

我们在其他地方使用akka-http来调用返回json响应的API,这种方法似乎在那里工作正常。 为什么它不起作用?我做错了什么?

任何建议表示赞赏。 感谢。

更新

添加byteStringFut.failed.foreach(println(_))会显示此异常:akka.http.scaladsl.model.EntityStreamException: HTTP chunk size exceeds the configured limit of 1048576 bytes

1 个答案:

答案 0 :(得分:0)

看起来出现了问题,异步计算中抛出异常。您可以通过以下方式检查Future来检查异常:

byteStringFut.failed.foreach(println)