Skip to content

How to do a RESTful POST Call

December 31, 2009

Hey everyone,

To go with the theme of web-based code snippets, here’s a little piece of code that will allow you to make RESTful HTTP Post calls!


public static HttpResponse doPost(String mUrl, HashMap<String, String> hm, String username, String password,

DefaultHttpClient httpClient) {

HttpResponse response = null;

if (username != null && password != null) {

httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),

new UsernamePasswordCredentials(username, password));

}

HttpPost postMethod = new HttpPost(mUrl);

if (hm == null) return null;

try {

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

Iterator<String> it = hm.keySet().iterator();

String k, v;

while (it.hasNext()) {

k = it.next();

v = hm.get(k);

nameValuePairs.add(new BasicNameValuePair(k, v));

}

postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));

response = httpClient.execute(postMethod);

Log.i(LOG_TAG, "STATUS CODE: " + String.valueOf(response.getStatusLine().getStatusCode()));

} catch (Exception e) {

Log.e("Exception", e.getMessage());

} finally {

}

return response;

}

So just a short explanation of what’s going on. The first part deals with setting an potential authentication parameters in order to complete the POST call (many times, if you are using say an exposed API, you may be required to pass in parameters such as a username and password). Then, we just use the built-in, standard HttpPost class, and finally we just encode any “form” parameters that need to get passed (for instance, if you are using something like a Facebook API, you might have to pass in the user id that you want to request information about, so your name value pair would look something like:


//example involving POST call to a Facebook API requesting data on user 123456789

nameValuePairs.add(new BasicNameValuePair("uid", 1234567890));

In my example, when I make the call I pass in all of the parameters as a HashMap (hence the hm parameter) but you can pass them in however you like – just wanted to make sure you got the general gist of how this all worked.

Happy coding.

– jwei

2 Comments leave one →
  1. cellurl permalink
    June 9, 2011 4:38 am

    How do you include a TIMEOUT mechanism?

    I would use your code, however my main reason I am rewritting my POST-code is to prevent lockup when the website or network is unavailable.

    I know there is a .connection(msTimeout) or some such mechanism, but I don’t know how to incorporate it into code such as your example above.

    Thanks!
    cellurl

Trackbacks

  1. Google App Engine – Bringing it Back To Android (4) « Think Android

Leave a comment