如何在java中发送带有post参数的简单http post请求

时间:2012-05-15 15:29:01

标签: java http post request

我需要一个简单的代码示例,使用从表单输入中获取的post参数发送http post请求。 我找到了Apache HTTPClient,它有很多API和许多复杂的例子,但我找不到一个简单的例子,用输入参数发送http post请求并获得文本响应。

更新:我对Apache HTTPClient v.4.x感兴趣,因为不推荐使用3.x.

5 个答案:

答案 0 :(得分:15)

以下是使用Apache HTTPClient API的Http POST的示例代码。

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

    }
}

答案 1 :(得分:4)

我从Andrew Gertig的Android项目中提取了这个代码,我在我的应用程序中使用过。它允许您执行HTTPost。如果我有时间,我会创建一个POJO示例,但希望您可以剖析代码并找到所需内容。

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

}

答案 2 :(得分:3)

使用Apache HttpClient v.4.x

的HTTP POST请求示例
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);

答案 3 :(得分:1)

http://httpunit.sourceforge.net/doc/cookbook.html 使用PostMethodWebRequest和setParameter方法

答案 4 :(得分:0)

显示了一个非常简单的示例,您可以从Html页面发布,servlet处理它并发送文本响应。

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

相关问题