Sending HTTP POST Request In Java(在 Java 中发送 HTTP POST 请求)
问题描述
让我们假设这个 URL...
lets assume this URL...
http://www.example.com/page.php?id=10
(这里的id需要在POST请求中发送)
(Here id needs to be sent in a POST request)
我想将 id = 10
发送到服务器的 page.php
,它以 POST 方法接受它.
I want to send the id = 10
to the server's page.php
, which accepts it in a POST method.
我如何在 Java 中做到这一点?
How can i do this from within Java?
我试过这个:
URL aaa = new URL("http://www.example.com/page.php");
URLConnection ccc = aaa.openConnection();
但我仍然不知道如何通过 POST 发送它
But I still can't figure out how to send it via POST
推荐答案
更新答案:
由于原始答案中的某些类在较新版本的 Apache HTTP 组件中已弃用,因此我发布此更新.
Updated Answer:
Since some of the classes, in the original answer, are deprecated in the newer version of Apache HTTP Components, I'm posting this update.
顺便说一句,您可以访问完整文档以获取更多示例 这里.
By the way, you can access the full documentation for more examples here.
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
}
}
原答案:
我推荐使用 Apache HttpClient.它更快更容易实现.
Original Answer:
I recommend to use Apache HttpClient. its faster and easier to implement.
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.
有关更多信息,请查看以下网址:http://hc.apache.org/
for more information check this url: http://hc.apache.org/
这篇关于在 Java 中发送 HTTP POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中发送 HTTP POST 请求
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01