How to send JSON POST data to a REST URL in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 15.11, “How to send JSON POST data to a REST URL in Scala.”


When writing Scala code, you want to send JSON data (or other data) to a POST URL, either from a standalone client, or when using a framework that doesn’t provide this type of service.


Create a JSON string using your favorite JSON library, and then send the data to the POST URL using the Apache HttpClient library. In the following example, the Gson library is used to construct a JSON string, which is then sent to a server using the methods of the HttpClient library:

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

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

object HttpJsonPostTest extends App {

    // create our object as a json string
    val spock = new Person("Leonard", "Nimoy", 82)
    val spockAsJson = new Gson().toJson(spock)

    // add name value pairs to a post object
    val post = new HttpPost("http://localhost:8080/posttest")
    val nameValuePairs = new ArrayList[NameValuePair]()
    nameValuePairs.add(new BasicNameValuePair("JSON", spockAsJson))
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs))

    // send the post request
    val client = new DefaultHttpClient
    val response = client.execute(post)
    println("--- HEADERS ---")
    response.getAllHeaders.foreach(arg => println(arg))


The Gson library is used to construct a JSON string in this code because this is a simple example. For more complex cases, you’ll probably want to use the Lift-JSON library, as discussed in the first several recipes of this chapter.

In this example, once you’ve constructed a JSON string from a Scala object, the Apache HttpClient NameValuePair, BasicNameValuePair, and UrlEncodedFormEntity classes are used to set an Entity on an HttpPost object. In the last lines of the code, the POST request is sent using the client.execute call, the response is received, and the response headers are printed (though this isn’t necessary).

See Also

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.