小编典典

用Java发送HTTP POST请求

java

让我们假设这个网址…

http://www.example.com/page.php?id=10 

(此处的ID需要在POST请求中发送)

我想将其发送id = 10到服务器的page.php,该服务器在POST方法中接受它。

如何在Java中执行此操作?

我尝试了这个:

URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();

但是我仍然不知道如何通过POST发送


阅读 2103

收藏
2020-02-25

共1个答案

小编典典

由于原始答案中的某些类已在Apache HTTP Components的较新版本中弃用,因此,我将发布此更新。

顺便说一句,你可以在此处访问完整的文档以获取更多示例。

HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/");

// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

if (entity != null) {
    try (InputStream instream = entity.getContent()) {
        // do something useful
    }
}
2020-02-25