By Alvin Alexander. Last updated: June 6, 2016
I created this Scala class as a way to test an HTTP POST request to a web service. Although its written in Scala, it uses the Apache HttpClient Java libraries. I got the NameValuePair code from the URL I've linked to.
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 object HttpPostTester { def main(args: Array[String]) { val url = "http://localhost:8080/posttest"; val post = new HttpPost(url) post.addHeader("appid","YahooDemo") post.addHeader("query","umbrella") post.addHeader("results","10") val client = new DefaultHttpClient val params = client.getParams params.setParameter("foo", "bar") val nameValuePairs = new ArrayList[NameValuePair](1) nameValuePairs.add(new BasicNameValuePair("registrationid", "123456789")); nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // send the post request val response = client.execute(post) println("--- HEADERS ---") response.getAllHeaders.foreach(arg => println(arg)) } }
Again, the primary reason for creating this HTTP POST client test class is to test the HTTP REST POST listener on the other end. I create these headers, parameters, and name value pairs here, then make sure I can process them properly in my POST server class.
There is some additional HTTP POST "entity" processing at this Apache URL:
http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientChunkEncodedPost.java