HttpClient入门

一、 导入jar

        <!--添加httpClient jar包 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

二、 HttpClient入门案例

    /**
     * 1.测试HttpClient中的get请求
     * 步骤:
     * 1.实例化httpClient对象
     * 2.确定访问url地址
     * 3.封装请求的类型get/post/put/delete
     * 4.发起http请求,获取响应对象response.
     * 5.校验返回对象的状态码信息.
     * 200表示成功
     * 400请求的参数异常
     * 404请求路径不匹配
     * 406请求的返回值类型异常
     * 500后台服务器运行异常
     * 504请求超时.后台服务器宕机/遇忙
     * 6.如果状态码信息为200,则动态的获取响应数据.
     * 7.获取返回值数据,之后进行业务调用.
     */
    @Test
    public void testGet() throws ClientProtocolException, IOException {
        HttpClient httpClient = HttpClients.createDefault();
        String url = "https://www.baidu.com";
        HttpGet httpGet = new HttpGet(url);
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            //表示用户请求成功!!
            HttpEntity entity = httpResponse.getEntity();//返回值数据的实体对象
            String json = EntityUtils.toString(entity, "utf-8");
            System.out.println(json);
        } else {
            //一定请求有误.
            System.out.println("服务器正忙,请稍后!!!");
        }
    }
    @Test
    public void testGet() throws ClientProtocolException, IOException {
        //定义httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String uri = "https://item.jd.com/5236335.html?dist=jd";
        HttpGet httpGet = new HttpGet(uri);
        //获取请求的全部参数   GET https://item.jd.com/5236335.html?dist=jd HTTP/1.1
        RequestLine requestLine = httpGet.getRequestLine();
        //获取请求方式     GET/POST
        requestLine.getMethod();
        //获取浏览器  http协议     HTTP/1.1
        requestLine.getProtocolVersion();
        //请求 uri:https://item.jd.com/5236335.html?dist=jd
        requestLine.getUri();
        //获取HTTP响应
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            System.out.println("获取请成功");
            //获取HTML
            String html = EntityUtils.toString(httpResponse.getEntity());
            System.out.println(html);
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值