HTTP POST example (submiting a simple form)

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: , , ,

Disabling Activity “slide” animation on StartActivity, Finish() and BackPressed

How to resize UIImage

Iterating through NSDictionary

CoreText CTFramesetterSuggestFrameSizeWithConstraints vs UILabel sizeWithFont

CoreText: set text font and alignment to CFAttributedString

CoreText example: Column Layout (correctly inverted text)

Changing UITableView width

Explode/split NSString

TouchXML installation guide

Parsing XML element attributes with TouchXML

UIColor cheatsheet: color list, conversion from and to RGB values

UINavigationBar with solid color or image background

Removing padding from UITextView

Getting NSDate from NSString

Getting day of the week from NSDate