JAVA post請求方式url_Java發送HTTP和POST請求的方式

一、概述

假設這個URL ...

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發送

二、詳解

推薦使用Apache HTTP Components開源專案進行操作。

您可以在此處訪問完整的檔案以取得更多範例:http://hc.apache.org/

例項:

HttpClient httpclient = HttpClients.createDefault();

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

// Request parameters and other properties.

List params = new ArrayList(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

}

}