Tuesday, October 12, 2010

HttpPost request

Most times an HTTP Get request is all that is required for your data gathering needs. Occasionally, though, you'll need to send an HTTP Post request. It's fairly simple, just different. Here's the code:

HttpConnectionParams.setConnectionTimeout(httpParameters, Constants.connectionTimeout);
HttpConnectionParams.setSoTimeout(httpParameters, Constants.socketTimeout);
HttpClient httpclient =  new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(Constants.MAIN_URL);
List<namevaluepair> nameValuePairs = new ArrayList<namevaluepair>(2);
nameValuePairs.add(new BasicNameValuePair("u", eUsername));
nameValuePairs.add(new BasicNameValuePair("p", ePassword));

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Create a response handler
 ResponseHandler<string> responseHandler = new BasicResponseHandler();
strResponseSaveGoal = httpclient.execute(httppost, responseHandler);

We need to make sure that nameValuePairs is set to the correct size of the list (in this case 2, because we have 2 parameters, u and p). Also, be sure to remember the ResponseHandler so that you can process the returned data.

No comments:

Post a Comment