http client 快速开始

官方文档地址http://hc.apache.org/httpcomponents-client-ga/quickstart.html

编辑工具:intelij idea

httpclient是自动化工程的第一步,两个步骤带你快速开始httpclient

1. 准备http请求

2. httpclient访问http请求

 

准备http请求

1.为了快速开始,选择基于本地准备http请求,方法选择创建spring boot项目(不用部署运行环境),在下准备的是sofa boot,差不多

2. 运行spring boot项目,运行成功后,访问地址:http://localhost:8082/json,如果能够访问成功,那就OK了

 

访问http请求

参照官方文档http://hc.apache.org/httpcomponents-client-ga/quickstart.html

使用方法:

1. 创建HttpClient对象

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse

稍作改变,代码如下

public class httpClient {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    @Test
    public void test() throws IOException {
        //String uri = "http://"+host+url;
        HttpGet httpGet = new HttpGet("http://localhost:8082/json2");
        CloseableHttpResponse response1 =  execute(httpGet);

        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }
    }

    public  CloseableHttpResponse execute(HttpUriRequest httpRequest) throws IOException {
        return httpclient.execute(httpRequest);
    }

}

返回结果

快速开始远远不够,对于项目需要继续封装

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值