HttpClient和RestTemplate总结

1 HttpClient

1.1 简介

HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送Http请求变得容易,而且也方便开发人员测试接口(基于Http协议的),提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。org.apache.commons.httpclient.HttpClient与org.apache.http.client.HttpClient的区别Commons的HttpClient项目现在是生命的尽头,不再被开发, 已被Apache HttpComponents项目HttpClient和HttpCore 模组取代,提供更好的性能和更大的灵活性。

1.2 HttpClient的请求类型

实现了所有的Http请求类型,相应的类为HttpGet、HttpPost、HttpDelete、HttpPut

1.3 导入依赖

在pom.xml中引入HttpClient的依赖

			<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpclient</artifactId>
            	<version>4.5.6</version>
			</dependency>

在pom.xml中引入fastjson的依赖

			<dependency>
            	<groupId>com.alibaba</groupId>
            	<artifactId>fastjson</artifactId>
            	<version>1.2.62</version>
			</dependency>

1.4 HttpGet

	public static void main(String[] args) throws IOException {
        //1.打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明get请求
        HttpGet httpGet = new HttpGet("http://www.baidu.com/s?wd=java");
        //3.发送请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //4.判断状态码
        if(response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
           //使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        }
        //5.关闭资源
        response.close();
        httpClient.close();
    }

1.5 HttpPost

	public static void main(String[] args) throws IOException {
        //1.打开浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明post请求
        HttpPost httpPost = new HttpPost("https://www.baidu.com/");
        //3.请求体
        StringEntity stringEntity = new StringEntity("{\"cname\":\"wuyin\",\"type\":\"SIMPLE\"});
        httpPost.setEntity(stringEntity);
 
        //4.发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //5.判断状态码
        if(response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        }
        //6.关闭资源
        response.close();
        httpClient.close();
    }

1.6 HttpPut

	public static void main(String[] args) throws IOException {
        //1.打开浏览器
        //HttpClientBuilder.create().build();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明post请求
        HttpPut httpPut = new HttpPut("https://www.baidu.com/");
        //3.请求体
        StringEntity stringEntity = new StringEntity("{\"cname\":\"wuyin\",\"type\":\"SIMPLE\"});
        httpPost.setEntity(stringEntity);
 
        //4.发送请求
        CloseableHttpResponse response = httpClient.execute(httpPut);
        //5.判断状态码
        if(response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        }
        //6.关闭资源
        response.close();
        httpClient.close();
    }

1.7 HttpDelete

	public static void main(String[] args) throws IOException {
        //1.打开浏览器
        //HttpClientBuilder.create().build();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.声明post请求
        HttpDelete httpDelete = new HttpDelete("https://www.baidu.com/");
        //3.请求体
        StringEntity stringEntity = new StringEntity("{\"cname\":\"wuyin\",\"type\":\"SIMPLE\"});
        httpPost.setEntity(stringEntity);
 
        //4.发送请求
        CloseableHttpResponse response = httpClient.execute(httpDelete);
        //5.判断状态码
        if(response.getStatusLine().getStatusCode()==200){
            HttpEntity entity = response.getEntity();
            String string = EntityUtils.toString(entity, "utf-8");
            System.out.println(string);
        }
        //6.关闭资源
        response.close();
        httpClient.close();
    }

2 RestTemplate

2.1 简介

RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果。默认情况下,RestTemplate默认依赖jdk的HTTP连接工具。可以通过setRequestFactory属性切换到不同的HTTP源,比如Apache HttpComponents、Netty和OkHttp。

2.2 请求方式

HttpMethodRestTemplateMethodsDescription
GETgetForObjectgetForObject函数实际上是对getForEntity函数的进一步封装,只关注返回的消息体的内容
getForEntitygetForEntity方法的返回值是一个ResponseEntity,ResponseEntity是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。
POSTpostForObject同理
postForEntity同理
postForLocationpostForLocation也是提交新资源,提交成功之后,返回新资源的URI,postForLocation的参数和前面两种的参数基本一致,只不过该方法的返回值为Uri,这个只需要服务提供者返回一个Uri即可,该Uri表示新资源的位置。
DELETEdelete请求服务器删除Request-URI所标识的资源
PUTput请求服务器存储一个资源,并用Request-URI作为其标识
OPTIONSoptionsForAllow请求查询服务器的性能,或者查询与资源相关的选项和需求
HEADheadForHeaders请求获取由Request-URI所标识的资源的响应消息报头

2.3 相关问题

  1. restTemplate的delete和put方法没有返回值,可能没法获取请求的返回。可以使用exchange方法和execute方法,可以指定请求类型。区别是exchange返回ResponseEntity,而execute返回消息体映射的对象。
  2. 使用方法中的uriVariables参数需要在url参数中使用占位符(暂时发现这一种)
	public void main(){
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        // 请求体
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map map = new HashMap(){{
            this.put("token","aaaa");
            this.put("project","bbbb");
        }};
        //提供json转化功能
        String str = "{\"cname\":\"wuyin3_bytemplate_123\"}";
        // 发送请求
        HttpEntity<String> entity = new HttpEntity<>(str, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> resultEntity = restTemplate.exchange
                ("http://XXXX?token={token}&project={project}", HttpMethod.PUT, entity, JSONObject.class,map);
        System.out.println(resultEntity.getBody());
    }
  1. RestTemplate能大幅简化了提交表单数据的难度,并且附带了自动转换JSON数据的功能
    在这里插入图片描述

2.4 相关链接

https://blog.csdn.net/u012702547/article/details/77917939

https://www.cnblogs.com/javazhiyin/p/9851775.html

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[2\]中提到,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,提高了开发的效率和代码的健壮性。而引用\[3\]中提到,RestTemplate默认依赖JDK提供的HttpURLConnection,但也可以通过设置HttpRequestFactory的方式集成其他Http客户端。因此,HttpClientRestTemplate性能上可能存在一些差别。 然而,具体的性能差别取决于多个因素,如网络环境、请求的复杂性、服务器的响应速度等。一般来说,HttpClient性能方面可能更优秀,因为它提供了更多的功能和灵活性,可以更好地处理复杂的请求和响应。而RestTemplate则更适合简单的HTTP请求和响应。 总的来说,如果你需要处理复杂的HTTP请求和响应,或者对性能有较高的要求,使用HttpClient可能更合适。而如果你只需要进行简单的HTTP请求和响应,或者希望与Spring框架更好地集成,使用RestTemplate可能更方便。最终的选择应该根据具体的需求和场景来决定。 #### 引用[.reference_title] - *1* *2* [HttpClientRestTemplate总结](https://blog.csdn.net/qq_38917188/article/details/116757134)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [HttpClient & RestTemplate](https://blog.csdn.net/weixin_44641388/article/details/121515758)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值