Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send simple http post request with post parameters in java

I need a simple code example of sending http post request with post parameters that I get from form inputs. I have found Apache HTTPClient, it has very reach API and lots of sophisticated examples, but I couldn't find a simple example of sending http post request with input parameters and getting text response.

Update: I'm interested in Apache HTTPClient v.4.x, as 3.x is deprecated.

like image 747
Arshak Avatar asked May 15 '12 15:05

Arshak


People also ask

Can we send parameters in POST request?

"In an HTTP POST request, the parameters are not sent along with the URI." - though it can be (just theoretically), do not confuse other people.

How do I send a body in a POST request?

Enter a Request Body As part of a POST, PUT, or PATCH request, a data payload can be sent to the server in the body of the request. When you select one of those methods from the method drop-down button, the API Connector form changes to display an input field for the request body.


2 Answers

Here's the sample code for Http POST, using Apache HTTPClient API.

import java.io.InputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;


public class PostExample {
    public static void main(String[] args){
        String url = "http://www.google.com";
        InputStream in = null;

        try {
            HttpClient client = new HttpClient();
            PostMethod method = new PostMethod(url);

            //Add any parameter if u want to send it with Post req.
            method.addParameter("p", "apple");

            int statusCode = client.executeMethod(method);

            if (statusCode != -1) {
                in = method.getResponseBodyAsStream();
            }

            System.out.println(in);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
like image 194
Sumit Desai Avatar answered Oct 14 '22 11:10

Sumit Desai


I pulled this code from an Android project by Andrew Gertig that I have used in my application. It allows you to do an HTTPost. If I had time, I would create an POJO example, but hopefully, you can dissect the code and find what you need.

Arshak

https://github.com/AndrewGertig/RubyDroid/blob/master/src/com/gertig/rubydroid/AddEventView.java

private void postEvents()
{
    DefaultHttpClient client = new DefaultHttpClient();

    /** FOR LOCAL DEV   HttpPost post = new HttpPost("http://192.168.0.186:3000/events"); //works with and without "/create" on the end */
    HttpPost post = new HttpPost("http://cold-leaf-59.heroku.com/myevents");
    JSONObject holder = new JSONObject();
    JSONObject eventObj = new JSONObject();

    Double budgetVal = 99.9;
    budgetVal = Double.parseDouble(eventBudgetView.getText().toString());

    try {   
        eventObj.put("budget", budgetVal);
        eventObj.put("name", eventNameView.getText().toString());

        holder.put("myevent", eventObj);

        Log.e("Event JSON", "Event JSON = "+ holder.toString());

        StringEntity se = new StringEntity(holder.toString());
        post.setEntity(se);
        post.setHeader("Content-Type","application/json");


    } catch (UnsupportedEncodingException e) {
        Log.e("Error",""+e);
        e.printStackTrace();
    } catch (JSONException js) {
        js.printStackTrace();
    }

    HttpResponse response = null;

    try {
        response = client.execute(post);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        Log.e("ClientProtocol",""+e);
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("IO",""+e);
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        try {
            entity.consumeContent();
        } catch (IOException e) {
            Log.e("IO E",""+e);
            e.printStackTrace();
        }
    }

    Toast.makeText(this, "Your post was successfully uploaded", Toast.LENGTH_LONG).show();

}
like image 22
dpott197 Avatar answered Oct 14 '22 10:10

dpott197