How to send simple http post request with post par

2019-01-14 08:52发布

问题:

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.

回答1:

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

    }
}


回答2:

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

}


回答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);


回答4:

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



回答5:

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