2

I want to 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?

hichris123
  • 10,145
  • 15
  • 56
  • 70
Neil.Lv
  • 161
  • 2
  • 8

2 Answers2

0

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.

Shaun the Sheep
  • 22,353
  • 1
  • 72
  • 100
pr1001
  • 21,727
  • 17
  • 79
  • 125
  • 1
    You can find that article here now: http://github.com/dpp/liftweb/wiki/How-To:-POST-XML-to-an-external-URL-with-Databinder-Dispatch now. – Nick Sep 18 '11 at 22:35
0

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.

Johan Prinsloo
  • 1,188
  • 9
  • 9