HttpClient的简单使用

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


HttpClient提供的主要的功能:

1、实现了所有的HTTP的方法(GET、POST、PUT、DELETE等)

2、支持自动转向

3、支持HTTPS协议

4、支持代理服务器等


GET请求:

    public static void main(String[] args) throws Exception {

        // 创建Httpclient对象	== 打开浏览器
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 定义请求的参数	==浏览器输入路径url
        URI uri = new URIBuilder("...url...").setParameter("wd", "java").setParameter("td", "php").build();

        System.out.println(uri);

        // 创建http GET请求
        HttpGet httpGet = new HttpGet(uri);

        CloseableHttpResponse response = null;
        try {
            // 发送请求	== 按回车,发出请求,并封装响应
            response = httpclient.execute(httpGet);
            // 状态码,和内容
            System.out.println(response.getStatusLine().getStatusCode());
            if (response.getEntity() != null) {
                String body = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(body);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            // == 关闭浏览器
            httpclient.close();
        }
    }


POST请求:

    public static void main(String[] args) throws Exception {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建http POST请求
        HttpPost httpPost = new HttpPost("...url...");

        //  {{{  设置 参数
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(10);
        parameters.add(new BasicNameValuePair("title", "HttpClient操作测试"));
        
        // 构造一个form表单的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"UTF-8");
        // 将请求实体设置到httpPost对象中    }}}     <------没有参数 不用写
        httpPost.setEntity(formEntity);

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 状态码和内容
            System.out.println(response.getStatusLine().getStatusCode());
            if (response.getEntity() != null) {
                String body = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(body);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

    }


PUT请求方式,与POST方式类似,不同点在于API:

post是HttpPost,而put是HttpPut。


DELETE请求方式,与GET方式类似,不同点在于API:

get是HttpGet,而delete是HttpDelete。







待续……








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值