9

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.

Arshak
  • 716
  • 2
  • 7
  • 15

5 Answers5

15

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();
        }

    }
}
Community
  • 1
  • 1
Sumit Desai
  • 1,542
  • 9
  • 22
  • Thank you, Sumit. I need such example, but your example is using Apache HttpClient v. 3.x, which is deprecated (even I couldn't find 3.x version jars in their download page). Now they suggest HttpClient v.4.1, which has different API, but I don't find how to put post parameters with this API. – Arshak May 16 '12 at 14:39
  • 3
    I have found the jars for httpClient v.3 and it works for me, but anyway I wonder why it's such complicated to send simple post request with v. 4.1 and in java in general. – Arshak May 16 '12 at 15:10
  • hi can you add additional parameter that accepts a file object? thanks – Secondo Jan 09 '16 at 05:50
4

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();

}
dpott197
  • 1,060
  • 1
  • 9
  • 11
3

HTTP POST request example using Apache HttpClient v.4.x

HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("param1", param1Value, ContentType.TEXT_PLAIN);
builder.addTextBody("param2", param2Value, ContentType.TEXT_PLAIN);
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
HttpResponse response = httpClient.execute(httpMethod);
Arshak
  • 716
  • 2
  • 7
  • 15
1

http://httpunit.sourceforge.net/doc/cookbook.html use PostMethodWebRequest and setParameter method

piotrek
  • 13,982
  • 13
  • 79
  • 165
0

shows a very simple exapmle where you do post from Html page, servlet processes it and sends a text response..

http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/servlet.html

Priyanshu Jha
  • 575
  • 5
  • 11