下面是关于 Java 使用 HttpClient 发送 POST 请求的完整攻略。
下面是关于 Java 使用 HttpClient 发送 POST 请求的完整攻略。
组件
在 Java 中发送 HTTP 请求,我们可以使用 Apache 的 HttpClient 组件,它提供了一系列的 API 帮助我们创建和发送请求。
在使用 HttpClient 组件之前,需要下载 HttpClient 组件的 jar 包,并将其添加到项目依赖中。
POST 请求
设置请求参数
发送 POST 请求需要设置请求参数,我们可以通过创建 Map 对象或者使用其他方式来设置请求参数,下面是以创建 Map 对象来设置请求参数的示例代码:
Map<String, String> params = new HashMap<>();
params.put("name", "张三");
params.put("age", "18");
params.put("sex", "男");
创建HttpPost对象
创建 HttpPost 对象,用于设置请求地址和请求参数:
HttpPost post = new HttpPost("http://localhost:8080/api/user");
post.setEntity(new UrlEncodedFormEntity(params, Charset.forName("UTF-8")));
发送请求并获取响应
使用 HttpClient 组件发送 HTTP 请求,然后获取响应结果:
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, Charset.forName("UTF-8"));
System.out.println(result);
}
示例
下面我们来看一下两个发送 POST 请求的示例。
示例1
发送 JSON 格式的 POST 请求:
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/api/user");
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("name", "张三");
jsonMap.put("age", "18");
jsonMap.put("sex", "男");
String jsonString = JSON.toJSONString(jsonMap);
StringEntity entity = new StringEntity(jsonString, ContentType.APPLICATION_JSON);
post.setEntity(entity);
CloseableHttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));
System.out.println(result);
}
示例2
发送 Form 格式的 POST 请求:
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("http://localhost:8080/api/user");
Map<String, String> params = new HashMap<>();
params.put("name", "张三");
params.put("age", "18");
params.put("sex", "男");
post.setEntity(new UrlEncodedFormEntity(params, Charset.forName("UTF-8")));
CloseableHttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity, Charset.forName("UTF-8"));
System.out.println(result);
}
以上就是 Java 使用 HttpClient 发送 POST 请求的完整攻略和两个示例。
沃梦达教程
本文标题为:java使用httpclient发送post请求示例
猜你喜欢
- 使用SpringBoot配置虚拟化路径用于图片的展示 2023-01-02
- springboot中如何通过main方法调用service或dao 2022-10-30
- synchronized背后的monitor锁实现详解 2023-05-14
- Java Timer使用讲解 2023-07-01
- JavaWeb Servlet中url-pattern的使用 2023-07-31
- Java模拟rank/over函数实现获取分组排名的方法详解 2024-01-30
- java数据库连接检索 2023-11-03
- SpringBoot静态资源的访问方法详细介绍 2023-06-06
- SpringBoot中如何解决读取properties文件读取问题 2023-02-27
- Apache ActiveMQ任意文件写入漏洞(CVE-2016-3088)复现 2023-12-10