httpClient(JAVA)

1.介绍

1.1 主要功能

1.实现了所有HTTP的方法(get、post、put、head等)

2.支持自动转向

3.支持代理服务器

4.自动处理set-cookie中的cookie

5.直接获取服务器发送的response code和headers

6.设置连接超时的能力

需要注意的是,httpclient版本的不同,功能实现的代码也就不同,需要谨慎。

1.2 步骤

  1. 创建HttpClient对象。

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

  3. 如果需要发送请求参数, 可调用HttpGet、 HttpPost共同的setParams(HetpParams params)方法来添加请求参数; 对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

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

  5. 调用HttpResponse的getAllHeaders()、 getHeaders(String name)等方法可获取服务器的响应头; 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。 程序可通过该对象获取服务器的响应内容。

  6. 释放连接。 无论执行方法是否成功, 都必须释放连接。

2.使用

2.1 get访问(不带参数)

在这里插入图片描述
在这里插入图片描述

    @Test
    public void get() throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://localhost:8080/ssm_crud/depts");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);

            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println("content = " + content);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            response.close();//关闭连接
            httpClient.close();//关闭浏览器
        }

    }

在这里插入图片描述
在这里插入图片描述
日志参考:slf4j以及实现类

2.2 get访问(带参数)

	@RequestMapping("/depts")
	@ResponseBody
	public Msg getDepts(@RequestParam("deptName")String deptName){
		//查出的所有部门信息
		List<Department> list = departmentService.getDepts();
		return Msg.success().add("depts", list).add("deptName",deptName);
	}
    @Test
    public void getWithParam() throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/ssm_crud/depts");

        uriBuilder.setParameter("deptName","NewDeptAAAAA");//中文的话,会乱码,要么设置tomcat,要么两次转码

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println("content = " + content);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            response.close();//关闭连接
            httpClient.close();//关闭浏览器
        }

    }

在这里插入图片描述

2.3 post访问(不带参数)

	@RequestMapping("/depts")
	@ResponseBody
	public Msg getDepts(){
		//查出的所有部门信息
		List<Department> list = departmentService.getDepts();
		return Msg.success().add("depts", list);
	}
    @Test
    public void post() throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://localhost:8080/ssm_crud/depts");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);

            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println("content2 = " + content);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            response.close();//关闭连接
            httpClient.close();//关闭浏览器
        }

    }

在这里插入图片描述

2.4 post访问(带参数)

	@RequestMapping("/depts2")
	@ResponseBody
	public Msg getDepts2(@RequestParam("deptName")String deptName){
		//查出的所有部门信息
		List<Department> list = departmentService.getDepts();
		return Msg.success().add("depts", list).add("deptName",deptName);
	}
    @Test
    public void postWithParam() throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://localhost:8080/ssm_crud/depts2");
        List<NameValuePair> param = new ArrayList<>();
        param.add(new BasicNameValuePair("deptName","新部门"));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(param, "utf-8");
        httpPost.setEntity(formEntity);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);

            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println("content2 = " + content);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            response.close();//关闭连接
            httpClient.close();//关闭浏览器
        }

    }

在这里插入图片描述

2.5 连接池

	@RequestMapping("/depts")
	@ResponseBody
	public Msg getDepts(){
		//查出的所有部门信息
		List<Department> list = departmentService.getDepts();
		return Msg.success().add("depts", list);
	}
    @Test
    public void conPool() throws Exception {

        PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
        //设置最大连接数
        pool.setMaxTotal(100);
        //设置每个主机的最大连接数
        pool.setDefaultMaxPerRoute(10);

        doGet(pool);
        doGet(pool);

    }


    private void doGet(PoolingHttpClientConnectionManager pool) throws Exception {
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pool).build();
        HttpGet httpGet = new HttpGet("http://localhost:8080/ssm_crud/depts");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);

            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println("content2 = " + content);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            response.close();//关闭连接
//            httpClient.close();//不能关闭
        }

    }

在这里插入图片描述

2.6 请求参数配置

    @Test
    public void get() throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://localhost:8080/ssm_crud/depts");


        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000)//创建连接最长时间
                .setConnectionRequestTimeout(500)//获取连接最长时间
                .setSocketTimeout(10 * 1000)//数据传输最长时间
                .build();

        httpGet.setConfig(config);
        
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);

            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println("content2 = " + content);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            response.close();//关闭连接
            httpClient.close();//关闭浏览器
        }

    }

参考

httpClient 官网
HttpClient详细使用示例
HttpClient 详细介绍

dvd

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值