12.HTTP client

1.HTTP client

        http client类似于spring cloud的feign,都是用于在应用程序之间发http请求

1.1 HTTP client使用

        在Java中,Apache HttpClient 是一个广泛使用的HTTP客户端库,它提供了丰富的功能和选项,用于发送HTTP请求和处理响应。

        导入依赖

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.4.1</version>
</dependency>

        测试发送请求

    /**
     * 测试httpclient发送get请求
     */
    @Test
    public void testGet() throws IOException {
        //创建httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        //创建请求对象
        HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");

        //发送请求
        CloseableHttpResponse execute = httpclient.execute(httpGet);

        //获取服务端返回的状态码
        int statusCode = execute.getStatusLine().getStatusCode();
        System.out.println(statusCode);

        HttpEntity entity = execute.getEntity();
        String body = EntityUtils.toString(entity);
        System.out.println(body);

        //关闭资源
        execute.close();
        httpclient.close();
    }
    /**
     * 测试httpclient发送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 execute = httpClient.execute(httpPost);

        int statusCode = execute.getStatusLine().getStatusCode();
        System.out.println("响应码为:"+statusCode);

        HttpEntity entity1 = execute.getEntity();
        String string = EntityUtils.toString(entity1);
        System.out.println("响应数据为:"+string);
    }

        使用可以直接用上传的工具类

猜你喜欢

转载自blog.csdn.net/LB_bei/article/details/132420467