HttpClient和RestTemplate

本文详细介绍了Spring的RestTemplate和Apache HttpClient在发起HTTP请求时的区别与使用方法。RestTemplate作为Spring提供的客户端工具,简化了HTTP请求操作,而HttpClient虽然功能强大但相对复杂,通常需要额外的封装。示例展示了使用HttpClient进行GET和POST请求的步骤,并对比了RestTemplate的简便用法,如getForEntity和postForEntity等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java请求网络资源通常用HttpClient等,Spring封装了库,提供更为简洁的资源请求方式RestTemplate
RestTemplate默认使用的是SimpleClientHttpRequestFactory工厂
默认它是以java.net下的HttpURLConnection方式发起的请求
所以RestTemplate是支持多种方式发起请求的
查看该工程的实现类可知,支持包括HttpClient, OkHttp等方式

HttpClient:代码复杂,还得操心资源回收等,代码很复杂,冗余代码多,不建议直接使用,一般是封装为 HttpUtils工具类使用
RestTemplate: 是 Spring 提供的用于访问Rest服务的客户端, RestTemplate 提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率

一、HttpClient

1、发起get无参请求

    @Test //get 无参
    public void doGet() {
    	String uri = "https://openapi.chanjet.com/auth/refreshToken?grantType=refresh_token&appKey=K2vIOn4m&refreshToken=1";
        // 1.创建Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2.创建Get请求
        HttpGet request = new HttpGet(uri);
        // 3.响应模型
        CloseableHttpResponse response = null;
        try {
            // 3.执行Get请求
            response = httpClient.execute(request);
            // 4.从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

2、发起post无参请求

    @Test //post 对象
    public void postObject() {
    	// 如果有普通参数,uri 改成 URIBuilder
        String uri = "http://localhost:8080/people/addPeople";
        // 创建Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();        
		// 创建Post请求
        HttpPost request = new HttpPost(uri);
        request.setHeader("Content-Type", "application/json;charset=utf8");
		// 添加json对象
        People people = new People();
        people.setName("张飞");
        people.setCreateTime(LocalDateTime.now());
        String jsonString = JSON.toJSONString(people);

        StringEntity entity = new StringEntity(jsonString, "UTF-8");
        httpPost.setEntity(entity);


        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 执行Post请求
            response = httpClient.execute(request);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity, StandardCharsets.UTF_8));
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

二、RestTemplate

1、发起get请求请求

发送一个HTTP GET请求,返回的请求体将映射为一个对象
getForObject()

发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
getForEntity()

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> entity = restTemplate.getForEntity(uri, String.class);
// TODO 处理响应

2、发起Post请求方式

postForEntity()
POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的。

postForObject()
POST 数据到一个URL,返回根据响应体匹配形成的对象。

postForLocation()
POST 数据到一个URL,返回新创建资源的URL

RestTemplate restTemplate = new RestTemplate();

// headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
HttpEntity<Object> objectHttpEntity = new HttpEntity<>(headers);

// TODO 处理响应
ResponseEntity<String> entity = restTemplate.postForEntity(uri, request, String.class);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值