如何在Java中发送带有POST参数的简单HTTP POST请求

9

我需要一个简单的代码示例,用于发送带有表单输入参数的HTTP POST请求。我已经找到了Apache HTTPClient,它有非常丰富的API和许多复杂的示例,但我找不到一个简单的示例,用于发送带有输入参数的HTTP POST请求并获取文本响应。

更新:我对Apache HTTPClient v.4.x感兴趣,因为3.x已被弃用。


http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html - Paul Vargas
5个回答

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

    }
}

谢谢,Sumit。我需要这样的例子,但是你的例子使用了已经被弃用的Apache HttpClient v.3.x版本(即使我在他们的下载页面上也找不到3.x版本的JAR包)。现在他们建议使用HttpClient v.4.1,它有不同的API,但我不知道如何使用这个API来设置POST参数。 - Arshak
3
我已经找到了httpClient v.3的jar包,并且它对我有效,但是无论如何,我想知道为什么使用v.4.1和Java一般情况下发送简单的post请求会这么复杂。 - Arshak
你好,你能否添加一个接受文件对象的额外参数?谢谢。 - Secondo

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

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

使用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);

1

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接