15.10. Sending JSON Data to a POST URL
Problem
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.
Solution
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
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
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 ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.