A Scala JSON (Gson) HTTP POST RESTful client example

While working on a Scala project recently I created the following example Scala code to test a variety of things, including:

  • Scala case classes
  • The Apache HttpClient classes, including HttpPost
  • Creating JSON with Gson
  • Sending the JSON object/string to my POST RESTful server

Given that brief introduction, here's the source code for my Scala HTTP client, which uses POST (Apache HttpPost) to send data to a RESTful web service:

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
import com.google.gson.Gson

case class Person(firstName: String, lastName: String, age: Int)

object HttpPostTester2 {

  def main(args: Array[String]) {

    // create our object as a json string
    val spock = new Person("Leonard", "Nimoy", 81)
    val spockAsJson = new Gson().toJson(spock)
    
    val url = "http://localhost:8080/posttest";
    val client = new DefaultHttpClient

    val post = new HttpPost(url)
    
    // add name value pairs
    val nameValuePairs = new ArrayList[NameValuePair]()
    nameValuePairs.add(new BasicNameValuePair("JSON", spockAsJson));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
    // send the post request
    val response = client.execute(post)
    println("--- HEADERS ---")
    response.getAllHeaders.foreach(arg => println(arg))
  }

}

I can add more information about this example if there are any questions, but until then, there's the code.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.