让我们假设这个网址…
http://www.example.com/page.php?id=10
(此处的ID需要在POST请求中发送)
我想将其发送id = 10到服务器的page.php,该服务器在POST方法中接受它。
id = 10
page.php
如何在Java中执行此操作?
我尝试了这个:
URL aaa = new URL("http://www.example.com/page.php"); URLConnection ccc = aaa.openConnection();
但是我仍然不知道如何通过POST发送
由于原始答案中的某些类已在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 } }