Adding JSON to the body of an HTTP POST request in Scala or Java

If you ever need to write some Scala (or Java) code where you add a JSON string to the body of an HTTP POST request, here's a quick example of how to do it using the Apache HttpClient library methods:

package foo

import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.DefaultHttpClient
import com.google.gson.Gson

object StockServletTester extends App {

  // create a Stock object
  val stock = new Stock("AAPL", 650.00)
  
  // convert it to a JSON string
  val stockAsJson = new Gson().toJson(stock)

  // create an HttpPost object
  val post = new HttpPost("http://localhost:8080/stocks/saveJsonStock")

  // set the Content-type
  post.setHeader("Content-type", "application/json")

  // add the JSON as a StringEntity
  post.setEntity(new StringEntity(stockAsJson))

  // send the post request
  val response = (new DefaultHttpClient).execute(post)

  // print the response headers
  println("--- HEADERS ---")
  response.getAllHeaders.foreach(arg => println(arg))

}

class Stock (var symbol: String, var price: Double) {
  override def toString = symbol + ", " + price
}

I added some comments to the source code, so there isn't much to add here, other than to say that it's written in Scala, and easily converts to Java.

More info: The Scalatra servlet

If you're comfortable with JSON and POST requests that example code can stand on its own, but if you also happen to know how to use the Scalatra library, this is what the corresponding Scalatra servlet looks like:

post("/saveJsonStock") {
  val jsonString = request.body
  try {
    val gson = new Gson
    val stock = gson.fromJson(jsonString, classOf[Stock])
    // for debugging
    println(stock)
    response.addHeader("ACK", "GOT IT")
  } catch {
      case e: Exception => 
        e.printStackTrace
        response.addHeader("ACK", "BOOM!")
  }
}

When I run the StockServletTester object against this servlet, it prints out the following output:

--- HEADERS ---
ACK: GOT IT
Content-Type: text/html;charset=UTF-8
Content-Length: 0
Server: Jetty(8.1.5.v20120716)

In summary, if you need to write a Scala or Java class to send a JSON string as the body of an HTTP POST request, I hope this example has been helpful.