August 2013
Intermediate to advanced
720 pages
16h 23m
English
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:
importjava.io._importorg.apache.commons._importorg.apache.http._importorg.apache.http.client._importorg.apache.http.client.methods.HttpPostimportorg.apache.http.impl.client.DefaultHttpClientimportjava.util.ArrayListimportorg.apache.http.message.BasicNameValuePairimportorg.apache.http.client.entity.UrlEncodedFormEntityimportcom.google.gson.GsoncaseclassPerson(firstName:String,lastName:String,age:Int)objectHttpJsonPostTestextendsApp{// create our object as a json stringvalspock=newPerson("Leonard","Nimoy",82)valspockAsJson=newGson().toJson(spock)// add name value pairs to a post objectvalpost=newHttpPost("http://localhost:8080/posttest")valnameValuePairs=newArrayList[NameValuePair]()nameValuePairs.add(newBasicNameValuePair("JSON",spockAsJson))post.setEntity(newUrlEncodedFormEntity(nameValuePairs))// send the post requestvalclient=newDefaultHttpClientvalresponse=client.execute(post)println("--- HEADERS ---")response.getAllHeaders ...
Read now
Unlock full access