Java之使用HttpClient发送GET请求

package com.zzuli.ajax.action;

/*
 * 使用Apache的HttpClient发送GET和POST请求的步骤如下:
 *   1. 使用帮助类HttpClients创建CloseableHttpClient对象.
 *   2. 基于要发送的HTTP请求类型创建HttpGet或者HttpPost实例.
 *   3. 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.
 *   4. 对于POST请求,创建NameValuePair列表,并添加所有的表单参数.然后把它填充进HttpPost实体.
 *   5. 通过执行此HttpGet或者HttpPost请求获取CloseableHttpResponse实例
 *   6. 从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.
 *   7. 最后关闭HttpClient资源.
 * */

/**
 * 使用HttpClient调用接口
 * 为性能测试写接口脚本
 */
public class GetChannelLine {
    public static void main(String args[]) throws Exception {
        String channelId = "sdd";
        String clientId = "123";
        // 目标地址
        String url = "http://XXX.XXX.com.cn/arowana/channel/getChannelLine?channelId=" + channelId + "&clientId=" + clientId;
        HttpGet httpGet = new HttpGet(url);

        // 设置类型 "application/x-www-form-urlencoded" "application/json"
        httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
        System.out.println("调用URL: " + httpGet.getURI());

        //        httpClient实例化
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 执行请求并获取返回
        HttpResponse response = httpClient.execute(httpGet);
        //        System.out.println("Response toString()" + response.toString());
        HttpEntity entity = response.getEntity();
        System.out.println("返回状态码:" + response.getStatusLine());

        //得到返回数据的长度;没有该参数返回-1
        //        if (entity != null) {
        //            System.out.println("返回消息内容长度: " + entity.getContentLength());
        //        }

        // 显示结果
        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
        String line = null;
        StringBuffer responseSB = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            responseSB.append(line);
        }
        System.out.println("返回消息:" + responseSB);
        reader.close();

        httpClient.close();
    }
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值