//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//以Post方式访问
HttpPost httpPost = new HttpPost("http://httpbin.org/post");
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
try {
//执行
CloseableHttpResponse response = httpClient.execute(httpPost);
log.info("状态码: {}\t\t{}", response.getCode(), response.getReasonPhrase());
HttpEntity entity = response.getEntity();
//获取响应数据
String content = EntityUtils.toString(entity);
log.info("content: {}", content);
//清理
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
引入:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>fluent-hc</artifactId>
</dependency>
代码简写:
try {
String content = Request.Post("http://httpbin.org/post")
.bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
.execute().returnContent().asString();
log.info("Content: {}", content);
} catch (IOException e) {
e.printStackTrace();
}