I’ll be super brief this time and post only the code snippet of my postComment function, which does, what it says that it does – collects data from several form fields and submits it via POST request to defined URL (script, which saves that data in a database or does whatever you’d like it to do).
private void postComment(){
EditText nameEdit = (EditText)findViewById(R.id.edit_name);
EditText commentEdit = (EditText)findViewById(R.id.edit_comment);
String name = nameEdit.getText().toString();
String comment = commentEdit.getText().toString();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://example.com/data/feedmepostrequests.php");
// set values you'd like to send
List pairs = new ArrayList();
pairs.add(new BasicNameValuePair("name", name));
pairs.add(new BasicNameValuePair("comment", comment));
pairs.add(new BasicNameValuePair("article_id", articleID));
// you probably won't need these two lines below, but I have to work with web service
// which has very annoying caching issues, so I usually pass some random argument
// to avoid possible failure
double r = Math.random();
pairs.add(new BasicNameValuePair("rand", "r"+r));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
// set ResponseHandler to handle String responses
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = client.execute(post, responseHandler);
Log.v("HttpPost", "Response: " + response);
if (response.contains("SUCCESS")){
// express your joy here!
} else {
// pop a sad Toast message here...
}
} catch (Exception e) {}
}
Tags: BasicResponseHandler, HttpClient, HttpPost, ResponseHandler