HTTP知识总结(二): Apache HttpClient 使用

参考:

1. Apache Httpclient tutorial
2. Jar包下载 

Apache Httpclient 是由apchae提供的http实现。虽然jdk的 java.net包提供了 HttpUrlconnection,但是功能和灵活性都有所欠缺。而apache httclient在效率和功能上有更好的表现。

使用httpclient,需要先到apache网站下载对应的jar包(下载地址)。使用到的jar包有:httpclient-xxx.jar, httpcore-xxx.jar, commons-logging-xxx.jara 等 (XXX为版本号,如httpclient-4.5.6.jar)

以下为实现get和post请求的简单实现:

Http GET

    public void testGet() {
        // 根据经纬度获取地址
        HttpClient httpClient = HttpClients.createDefault();
        String url = "http://gc.ditu.aliyun.com/regeocoding?l=34.267673,117.305076&type=111";

        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);

            // 解析返回数据
            parse(response.getEntity().getContent(), "UTF-8");

        } catch (IOException ex) {

        }
    }

Http POST

public void testPost() {

        // 获取手机号归属地信息
        try {
            String url = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
            HttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);

            // Post参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("tel", "18951848769"));
            post.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse response = client.execute(post);
            // 解析返回数据
            //parse(response.getEntity().getContent(), "GB2312");
        } catch (Exception ex) {

        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值