By Alvin Alexander. Last updated: July 23, 2016
This Scalatra POST method shows one way to handle HTTP POST data. It shows that you can access POST parameters using the Scalatra params function:
post("/msgs") { val builder = MongoDBObject.newBuilder builder += "author" -> params.get("author") builder += "msg" -> params.get("msg") coll += builder.result.asDBObject redirect("/msgs") }
This works fine with a Scala HTTP POST test client I created. In particular I can access the name/value pairs that are created in the POST client below:
package tests import java.io._ import org.apache.commons._ import org.apache.http._ import org.apache.http.client._ import org.apache.http.client.methods.HttpPost import org.apache.http.impl.client.DefaultHttpClient import java.util.ArrayList import org.apache.http.message.BasicNameValuePair import org.apache.http.client.entity.UrlEncodedFormEntity /** * This is a Scala HTTP POST client. I created it to test my Scalatra POST server side method. */ object HttpPostTester { def main(args: Array[String]) { val url = "http://localhost:8080/posttest"; val client = new DefaultHttpClient // add header elements val post = new HttpPost(url) post.addHeader("appid","YahooDemo") post.addHeader("query","umbrella") post.addHeader("results","10") // add name value pairs (works with "params" function on the server side) val nameValuePairs = new ArrayList[NameValuePair](1) nameValuePairs.add(new BasicNameValuePair("registrationid", "123456789")); nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // send the post request val response = client.execute(post) println("--- HEADERS ---") response.getAllHeaders.foreach(arg => println(arg)) } } r