httpclient 小案例(未完待续)

为了调用微信小程序接口,我们可以使用httpclient 

导入依赖:

httpclient 小案例(未完待续)_第1张图片

 

java通过编码方式里发http请求,步骤:

  1. 创建http client 对象
  2. 创建http请求对象(get或post)
  3. 调用http client excute方法

httpGet请求方法

@Test
    public void testGet() throws IOException {
        //1\创建client对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2\创建请求对象
        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 body = EntityUtils.toString(entity);
        System.out.println("响应信息"+body);
        response.close();
        httpClient.close();
    }

httpPost请求方法

@Test
    public void testPost() throws IOException {
        //1\创建client对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2\创建请求对象
        HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
        //3\发送请求
        //传一个json对象
        Employee employee = Employee.builder().username("admin").password("123456").build();
        StringEntity entity = new StringEntity(JSON.toJSONString(employee));
        entity.setContentType("application/json");
        entity.setContentEncoding("utf-8");
        httpPost.setEntity(entity);
        //获取状态码
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //解析数据 获取状态吗
        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("响应码"+statusCode);
        //解析数据 获取信息
        HttpEntity entity1 = response.getEntity();
        String body = EntityUtils.toString(entity1);
        System.out.println("响应信息"+body);
        response.close();
        httpClient.close();
    }

输出结果

 

你可能感兴趣的:(http)