HttpClient基础使用

HttpClient Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

1.导入依赖

<!--        httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>

2.发送get请求

@Test
    public void test() throws IOException {
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

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

        //发送请求,接受响应结果
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        //解析响应结果
        //获取响应码
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        System.out.println("响应码是"+statusCode);

        //获取响应体
        HttpEntity entity = httpResponse.getEntity();
        String string = EntityUtils.toString(entity);
        System.out.println("响应体是"+string);

        //关闭资源
        httpClient.close();
        httpResponse.close();
    }

3.发送post请求

 @Test
    public void testpost() throws IOException, JSONException {
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建post请求对象
        HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");

        //创建json对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username","admin");
        jsonObject.put("password","123456");

        //设置请求参数
        StringEntity stringEntity = new StringEntity(jsonObject.toString());
        //指定编码方式
        stringEntity.setContentType("UTF-8");
        //指定数据格式
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);

        //发送请求,接受响应结果
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

        //解析响应结果
        //获取响应码
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        System.out.println("响应码是"+statusCode);

        //获取响应体
        HttpEntity entity = httpResponse.getEntity();
        String string = EntityUtils.toString(entity);
        System.out.println("响应体是"+string);

        //关闭资源
        httpClient.close();
        httpResponse.close();
    }

心得:

jsonObject可以创建json对象,使用put方式添加元素。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值