HttpClient实例

HttpClient

1.1 get请求

 @Test
    public void testGet() throws IOException {
        //1. 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 2. 创建get请求对象,指定请求url
        HttpGet httpGet = new HttpGet("http://localhost:8080/admin/shop/status");
        //3. 发送请求,接受响应结果
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 4. 解析结果
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("响应码:"+statusCode);

        HttpEntity entity = response.getEntity();
        String body = EntityUtils.toString(entity);

        System.out.println("响应体:"+body);

        // 5. 关闭资源
        response.close();
        httpClient.close();

1.2 post请求

 @Test
    public void testPost() throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");


        // 请求参数
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("username","admin");
        jsonObject.put("password","123456");

        StringEntity entity = new StringEntity(jsonObject.toString());

        entity.setContentEncoding("utf-8");
//数据格式
        entity.setContentType("application/json");
        httpPost.setEntity(entity);

        CloseableHttpResponse response = httpClient.execute(httpPost);
    // 解析执行结果
    // 响应头
        int code =response.getStatusLine().getStatusCode();
        System.out.println("响应码为:"+code);
// 响应内容
        HttpEntity entity1 = response.getEntity();
        String body = EntityUtils.toString(entity1);
        System.out.println("响应体:"+body);

        response.close();
        httpClient.close();
    }

你可能感兴趣的:(java项目实战,httpclient)