drew moore
drew moore

Reputation: 32680

How to execute RESTful POST requests from Android

I'm trying to execute a REST Post for the first time and I don't quite know where to begin.

I'm interacting with the WordPress REST API, and am trying to utilize this endpoint: /sites/$site/posts/$post_ID/replies/new, which is used to submit a new comment to a certain post.

I think I have a good grasp on working with GET requests, as I've successfully handled several of them. With those, I could say everything I needed to say to the server vis a vis the URL, but it seems there must be another step with POST requests. And my question is: What is that step(s)?

Do I wrap the content I want to submit into a JSONObject and post that? If so, how do I post it? Do I need to construct a statement somehow, similar to how I would construct a statement to execute on a database? Or is it indeed possible to pass my content along via the URL, as request parameters?

I'm aware that this question is a little on the open-ended side for SO, but I've been unable to find a good tutorial that answers these questions. If you know of one, please suggest it.

(I'm doing this all in an Android app)

Upvotes: 5

Views: 12190

Answers (2)

brendosthoughts
brendosthoughts

Reputation: 1703

My answer is taken straight from another answer on SO seen here Sending POST data in Android but ive cut and past the answer here for conveneience, Hope this helps

Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

Upvotes: 7

Junaid
Junaid

Reputation: 7860

You need to implement a script on your server, your POST interacts with that script and inturn that script works with your database.

A typical scenario will be:

Java HTTP POST ~~~> PHP ~~~~> MySql.

A good starting point to learn PHP will be to checkout PHPAcademy tutorials on youtube.

http://www.youtube.com/course?list=EC442FA2C127377F07

PHP will as well help you encode the result in JSON and post it back to your client.

Upvotes: 0

Related Questions