java - 在 Java 中发送 HTTP POST 请求

标签 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 组件中已弃用,因此我发布此更新。

顺便说一句,您可以访问完整文档以获取更多示例 here .

HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.example/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
    }
}

原答案

我推荐使用 Apache HttpClient。它更快更容易实现。

HttpPost post = new HttpPost("http://jakarata.apache.org/");
NameValuePair[] data = {
    new NameValuePair("user", "joe"),
    new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.

有关更多信息,请查看此 URL:http://hc.apache.org/

关于java - 在 Java 中发送 HTTP POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3324717/

相关文章:

http - 从 Heroku 访问仅限于静态 IP 地址的 API 的好策略是什么?

javascript - Function "overruns"执行期间的if-else语句

java - j2me网络

java - GWT 中的单元表

java - Android JSON解析错误未确定的对象

javascript - 如何在 jQuery.post 中使用动态数据名称?

java - 如何让RESTful java客户端在Openstack上发送GET/POST请求?

java - 为什么Spring-proxy使用委托(delegate)模式而不是继承+super?

http - 检测 HttpServlet 中中止的请求

api - 每 X 分钟向我发送一次 HTTP GET 请求