目标是使用 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中文网其他相关文章!