12.HTTP client

博客介绍了HTTP client,它类似于spring cloud的feign,用于应用程序间发http请求。重点讲述了在Java里,广泛使用的Apache HttpClient库,给出了导入依赖的代码示例,还提到测试发送请求可使用上传的工具类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
    }

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值