Recipe 6.2 Connecting to Servers Using HTTP POST

Android Versions
Level 1 and above
Source Code to Download at

The previous recipe showed how to connect to a server using HTTP GET, whereby the data to pass to the server is appended to the end of the URL. Instead of using HTTP GET, you can also use the alternative HTTP POST method. With HTTP GET, all the data passed to the server is contained in the URL, and it is typically constrained in size (typically less than 2,000 characters). With HTTP POST you can send the data separately to the server, essentially bypassing the data size limit. This recipe demonstrates how to connect to a web server using HTTP POST.


To connect to a server using HTTP POST, use the HttpClient, HttpPost, and HttpResponse classes, as shown here:

 //---Connects using HTTP POST--- public InputStream OpenHttpPOSTConnection(String url) { InputStream inputStream = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); //---set the headers--- httpPost.addHeader("Host", ""); httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); //---the key/value pairs to post to the server--- List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("FromCurrency", "USD")); nameValuePairs.add(new BasicNameValuePair("ToCurrency", "SGD")); httpPost.setEntity(new ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.