开发者

How to use the scala dispatch library to send a post request to the server in the Lift?

开发者 https://www.devze.com 2022-12-17 19:51 出处:网络
I want t开发者_StackOverflow中文版o use the scala dispatch library to send a post request to the server in the Lift.

I want t开发者_StackOverflow中文版o use the scala dispatch library to send a post request to the server in the Lift.

I want to send a post request to the external server and get some information and then use this information in my web app.

How can I do this?


The Lift GitHub Wiki (which is being replaced by the Assembla one), has an article on using Dispatch along the lines of what you're seeking.


Here is a snippet that dispatches REST calls to a server:

    val http = new Http
    val call = parse(event.call)
    val verbspec = (call \ "verb").values toString
    val urlspec = (call \ "url").values toString
    val namespec = (call \ "username").values toString
    val pwspec = (call \ "password").values toString

    val req = url(urlspec).as(namespec, pwspec) <:< Map("Content" -> "application/json")

    val (status: Int, contentWrap,  headers) = verbspec match {
      case "GET" => {
        http x (( req >:> identity ) {
          case (200, _, Some(thing),  out) => {
            val resp = fromInputStream(thing.getContent()).getLines.mkString
            (200, Some(resp), out())
          }
          case (badCode, _, _, out) => (badCode, None, out())
        })
      }
      case "POST" => {
        http x (( req.POST << (event.payload) >:> identity ) {case (status,  _, _, out) => (status,  None, out()) })
      }
      case "PUT" => {
        http x (( req.PUT <<< (event.payload) >:> identity ) {case (status,  _, _,  out) => (status,  None, out()) })
      }
      case _ => {
        EventHandler.error(this, "Bad verb specified")
        (000,  None, Map.empty)
      }
    }

Where:

event.call -> json specifying the call

event.payload -> json payload for PUT and POST

http x -> http://databinder.net/dispatch-doc/#dispatch.Http

>:> -> http://databinder.net/dispatch-doc/#dispatch.HandlerVerbs

<< , <<< , <:< -> http://databinder.net/dispatch-doc/#dispatch.RequestVerbs

This uses Lift JSON for parsing the call spec and executes in a Akka actor. Status, headers and content is returned to the calling actor.

0

精彩评论

暂无评论...
验证码 换一张
取 消