玩!框架使用异步Web请求编写操作

时间:2013-11-27 20:58:59

标签: scala playframework playframework-2.0

我对Scala很新 我正试图从Play访问Instagram API!和斯卡拉。

def authenticate = Action {
request =>
  request.getQueryString("code").map {
    code =>
      WS.url("https://api.instagram.com/oauth/access_token")
        .post(
        Map("client_id" -> Seq(KEY.key), "client_secret" -> Seq(KEY.secret), "grant_type" -> Seq("authorization_code"),
          "redirect_uri" -> Seq("http://dev.my.playapp:9000/auth/instagram"), "code" -> Seq(code))
      ) onComplete {
        case Success(result) => Redirect(controllers.routes.Application.instaline).withSession("token" -> (result.json \ "access_token").as[String])
        case Failure(e) => throw e
      }
  }
 Redirect(controllers.routes.Application.index)

}

当应用程序执行时,最后一次重定向在重定向之前发生,以防成功。 请告诉我,如何避免它。另外,请告诉我代码中的不良做法。

1 个答案:

答案 0 :(得分:5)

使用Play,您会返回结果 - 您不会发送结果。 onComplete方法附加了一个执行某些操作的方法,但不返回任何内容(请注意其返回值为Unit,即void)。在附加该回调之后,您将在最后一行返回Redirect,这不是您想要做的。相反,您希望map从WS调用中获得的未来,并返回该未来。要在Play中返回未来,您需要使用Action.async构建器。例如:

def authenticate = Action.async { request =>

  request.getQueryString("code").map { code =>

    WS.url("https://api.instagram.com/oauth/access_token").post(
      Map(
        "client_id" -> Seq(KEY.key),
        "client_secret" -> Seq(KEY.secret),
        "grant_type" -> Seq("authorization_code"),
        "redirect_uri" -> Seq("http://dev.my.playapp:9000/auth/instagram"),
        "code" -> Seq(code)
      )
    ).map { result =>

      Redirect(controllers.routes.Application.instaline)
        .withSession("token" -> (result.json \ "access_token").as[String])

    }
  }.getOrElse {
    Future.successful(Redirect(controllers.routes.Application.index))
  }
}
相关问题