是apache旗下的项目 可以用来提供高效的 最新的 功能丰富的 支持HTTP协议的客户端编程工具包,并且支持HTTP协议最新的版本和建议
核心API
- HttpClient
- HttpClients
- CloseableHttpClient
- HttpGet
- HttpPost
发送请求步骤
- 创建HttpClient对象
- 创建Http请求对象
- 调用HttpClient的excute方法发送请求
HttpGet请求
@Test public void TestGet() throws IOException { //1.创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); //2.创建Http请求对象 HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status"); //3.发送请求 CloseableHttpResponse response = httpClient.execute(httpGet) ; //获取请求返回的状态码 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("返回的状态码:"+statusCode); //获取请求返回的数据 HttpEntity entity = response.getEntity(); String code = EntityUtils.toString(entity); System.out.println("返回的数据"+code); //4.关闭资源 response.close(); httpClient.close(); }
Http的Post请求
@Test public void TestPost01() throws IOException { //1.创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); //2.创建请求对象 HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login"); //3.发送请求 //获取一个json对象 JSONObject jsonObject = new JSONObject(); //给该json赋值 jsonObject.put("username", "admin") ; jsonObject.put("password", "123456") ; //获取一个Entity对象 StringEntity stringEntity = new StringEntity(jsonObject.toString()) ; //给post请求设置请求体 httpPost.setEntity(stringEntity) ; //发送请求 CloseableHttpResponse response = httpClient.execute(httpPost); System.out.println(response.getStatusLine().getStatusCode());//打印状态码 System.out.println(EntityUtils.toString(response.getEntity())); //打印返回体字符串 //4.关闭资源 response.close(); httpClient.close(); }