目標是使用 POST 方法將資料(id = 10)傳送到遠端伺服器。提供的 Java 程式碼嘗試開啟到遠端 URL 的連接,但無法指定 POST 請求參數。
Apache HttpClient 是一個流行的用於發送和接收的 Java 庫HTTP 請求。以下是如何使用它在 Java 中實現 POST 功能:
HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://www.example.com/page.php"); // Request parameters List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("id", "10")); // Set request parameters encoded in UTF-8 as POST body httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); // Execute the HTTP POST request HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); // Handle response if (entity != null) { // Process response body, e.g., print the HTML content InputStream instream = entity.getContent(); }
在此更新的解決方案中,舊版 Apache HTTP 元件中已棄用的類別已替換為較新的等效項。
以上是如何使用 Apache HttpClient 在 Java 中發送帶有參數的 POST 請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!