【苍穹外卖】HttpClient-快速理解&入门
@Test
void testPost() throws Exception {
//获取httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//url地址
String url = "http://localhost:8080/admin/employee/login";
//获取HttpPost对象
HttpPost httpPost = new HttpPost(url);
//模拟请求体数据--数据格式为json
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", "admin");
jsonObject.put("password", "123456");
//设置请求体参数对象-这里HttpEntity的实现类-StringEntity
StringEntity stringEntity = new StringEntity(jsonObject.toJSONString());
httpPost.setEntity(stringEntity);
//设置请求编码格式
stringEntity.setContentEncoding("utf-8");
//设置请求体数据格式
stringEntity.setContentType("application/json");
//发送post请求
CloseableHttpResponse response = httpClient.execute(httpPost);
//获取返回数据
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("状态响应码:" + statusCode);
HttpEntity entity = response.getEntity();
//将返回的实体类解析为字符串
String resultData = EntityUtils.toString(entity);
System.out.println("返回数据:" + resultData);
//关闭资源
response.close();
httpClient.close();
}