SpringBoot RestTemplate 的使用

一、简介

RestTemplate 在JDK HttpURLConnection、Apache HttpComponents、OkHttp等基础上,封装了更高级别的API,默认依赖JDK HttpURLConnection,连接方式默认长连接。

二、使用

2.1、引入依赖

<dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId>
</dependency>

2.2、创建RestTemplate 

2.2.1、配置参数 

http:maxTotal: 100         #最大连接数defaultMaxPerRoute: 20  #并发数connectTimeout: 1000   #创建连接的最长时间connectionRequestTimeout: 500  #从连接池中获取到连接的最长时间socketTimeout: 10000 #数据传输的最长时间staleConnectionCheckEnabled: true  #提交请求前测试连接是否可用validateAfterInactivity: 3000000   #可用空闲连接过期时间,重用空闲连接时会先检查是否空闲时间超过这个时间,如果超过,释放socket重新建立

2.2.2、建立Bean注入 IOC 

import org.apache.http.Header;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;import java.util.ArrayList;
import java.util.List;@Configuration
public class RestTemplateConfig {@Value("${http.maxTotal}")private Integer maxTotal;@Value("${http.defaultMaxPerRoute}")private Integer defaultMaxPerRoute;@Value("${http.connectTimeout}")private Integer connectTimeout;@Value("${http.connectionRequestTimeout}")private Integer connectionRequestTimeout;@Value("${http.socketTimeout}")private Integer socketTimeout;@Value("${http.staleConnectionCheckEnabled}")private boolean staleConnectionCheckEnabled;@Value("${http.validateAfterInactivity}")private Integer validateAfterInactivity;@Beanpublic RestTemplate restTemplate() {return new RestTemplate(httpRequestFactory());}/*** 使用 Apache HttpClient 作为底层客户端* 效率: OkHttp > Apache HttpClient > JDK HttpURLConnection*/@Beanpublic ClientHttpRequestFactory httpRequestFactory() {return new HttpComponentsClientHttpRequestFactory(httpClient());}@Beanpublic HttpClient httpClient() {Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build();PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);connectionManager.setMaxTotal(maxTotal); // 最大连接数connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);    // 单个路由最大连接数connectionManager.setValidateAfterInactivity(validateAfterInactivity); // 最大空间时间RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)        // 服务器返回数据(response)的时间,超过抛出read timeout.setConnectTimeout(connectTimeout)      // (握手成功)的时间,超出抛出connect timeout.setStaleConnectionCheckEnabled(staleConnectionCheckEnabled) // 提交前检测是否可用.setConnectionRequestTimeout(connectionRequestTimeout)// 从连接池中获取连接的超时时间,超时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool.build();// headersList<Header> headers = new ArrayList<>();headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));headers.add(new BasicHeader("Accept-Language", "zh-CN"));headers.add(new BasicHeader("Connection", "Keep-Alive"));headers.add(new BasicHeader("Content-type", "application/json;charset=UTF-8"));return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager).setDefaultHeaders(headers)// 保持长连接配置,需要在头添加Keep-Alive.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())// 重试次数,默认是3次,没有开启.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true)).build();}
}

2.3、API 使用 

2.3.1、GET请求 

public <T> T getForObject(...):返回值是HTTP协议的响应体内容。
public <T> ResponseEntity<T> getForEntity(...):返回的是ResponseEntity,ResponseEntity包含响应体、HTTP状态码、contentType、contentLength、Header等信息。

Map<String,Object> map = new HashMap<>();
map.put("name","aaa");
map.put("age",12);
// 表单提交传参
ResponseEntity<R> responseEntity = restTemplate.getForEntity(url,R.class,map);

2.3.2、POST请求

public URI postForLocation(...):用POST创建一个新资源,返回UTI对象,可从响应中返回Location报头。
public <T> T postForObject(...):返回HTTP协议的响应体body内容。
public <T> ResponseEntity<T> postForEntity(...):返回ResponseEntity,ResponseEntity包含响应体、HTTP状态码、contentType、contentLength、Header等信息。

RestTemplate restTemplate = new RestTemplate();
String url = "http://172.18.20.200:8080/cms/work/queryWorks";
JSONObject jsonObject = new JSONObject();
jsonObject.set("state","01");
jsonObject.set("title","aaaaa");
// Json 传参
ResponseEntity<R> responseEntity = restTemplate.postForEntity(url,jsonObject,R.class);
System.out.println("---ret-getBody: " +responseEntity.getBody());
System.out.println("---ret-getBody-getCode: " +responseEntity.getBody().getCode());
System.out.println("---ret-getBody-getData: " +responseEntity.getBody().getData());# POST以表单方式提交
//请求地址
String url2 = "......";
//设置请求头, x-www-form-urlencoded格式的数据
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//提交参数设置
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("name","aaaaaa");
//组装请求体
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, httpHeaders);
//发送post请求并打印结果 以String类型接收响应结果JSON字符串
String s = restTemplate.postForObject(url2, request, String.class);
System.out.println(s);

2.3.3、PUT、DELETE请求 

PUT请求
一般用来新增或修改资源,没返回值。String url = "......";User user = new User();user.setName("鲁大师");restTemplate.put(url,user);DELETE请求
没返回值,与PUT请求一样。

2.3.4、EXECUTE

RestTemplate restTemplate = new RestTemplate();
//请求地址
String url = "http://172.18.20.200:8080/cms/work/queryWorks";
User user = new User();
user.setName("aaa");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<User> userHttpEntity = new HttpEntity<User>(user, httpHeaders);
ResponseEntity<Object> execute = restTemplate.execute(url, HttpMethod.POST, restTemplate.httpEntityCallback(userHttpEntity), restTemplate.responseEntityExtractor(Object.class));
System.out.println(execute);

2.3.5、上传、下载文件

上传文件//需要上传的文件String filePath = "/C:/cms/aaa.jpg";//请求地址String url = "http://localhost:8080/rest/file/test/post/upload";// 请求头设置,multipart/form-data格式的数据HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.MULTIPART_FORM_DATA);//提交参数设置MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();param.add("multipartFile", new FileSystemResource(new File(filePath)));param.add("userCode", "anightmonarch");param.add("userName", "一宿君");// 组装请求体HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(param, headers);//发起请求ResponseBean responseBean = restTemplate.postForObject(url, request, ResponseBean.class);System.out.println(responseBean);下载文件//需要下载的文件String fileName = "121dfga0ab3ba.jpg";//用户信息String userId = "123456789";//请求地址String url = "......";//提交参数设置Map<String,Object> paramMap = new HashMap<String,Object>();paramMap.put("fileName",fileName);paramMap.put("userId",userId);//发起请求(响应内容为字节文件)ResponseEntity<byte[]> response = restTemplate.getForEntity(url, byte[].class, paramMap);System.out.println("HTTP 响应状态:" + response.getStatusCode());//下载文件保存路径File savePath = new File("C:\\cms\\download\\img\\");if (!savePath.isDirectory()){savePath.mkdirs();}Path path = Paths.get(savePath.getPath() + File.separator + fileName);Files.write(path, Objects.requireNonNull(response.getBody(),"下载文件失败!"));

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/228428.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Python财经股票数据保存表格文件 <雪球网>

嗨喽&#xff0c;大家好呀~这里是爱看美女的茜茜呐 环境使用: Python 3.10 解释器 Pycharm 编辑器 &#x1f447; &#x1f447; &#x1f447; 更多精彩机密、教程&#xff0c;尽在下方&#xff0c;赶紧点击了解吧~ python源码、视频教程、插件安装教程、资料我都准备好了&…

如果每天工资按代码行数来算,来看看你每天工资是多少

说在前面 &#x1f63c;&#x1f63c;如果每天的工资取决于我们所编写的代码行数&#xff0c;那么我们的生活会发生怎样的改变&#xff1f;来看看你的同事们今天都提交了多少代码吧&#xff0c;看看谁是卷王&#xff0c;谁在摸鱼&#xff08;&#x1f436;&#x1f436;狗头保命…

SLURM资源调度管理系统REST API服务配置,基于slurm22.05.9,centos9stream默认版本

前面给大家将了一下slurm集群的简单配置&#xff0c;这里给大家再提升一下&#xff0c;配置slurm服务的restful的api&#xff0c;这样大家可以将slurm服务通过api整合到桌面或者网页端&#xff0c;通过桌面或者网页界面进行管理。 1、SLURM集群配置 这里请大家参考&#xff1…

STM32F407-14.3.5-01捕获_比较通道

捕获/比较通道 每一个捕获/比较通道都是围绕着一个捕获/比较寄存器(包含影子寄存器) 包括: 捕获的输入部分(数字滤波、多路复用和预分频器)&#xff0c; 输出部分(比较器和输出控制)。 中文参考手册中框图分成了三大模块, 把框图合并成了一个整体,以便更好的理解捕获输…

仿东郊到家预约按摩小程序开发;

在这个快节奏的现代社会&#xff0c;人们对便捷、高效的服务需求日益增大。正因如此&#xff0c;到家预约系统上门按摩小程序应运而生&#xff0c;它结合了互联网技术和传统按摩服务&#xff0c;不仅满足了人们对便捷按摩服务的需求&#xff0c;还为商家提供了全新的商业价值。…

js数组中,相同id的item数据合并

原数据&#xff1a; const list [ {id:1, key: a}, {id:1, key: b}, {id:2, key: c}, {id:2, key: d}, ]期望数据格式 const newList [ {id:1, keyList: [a,b]}, {id:2, keyList: [c,d]}, ]// 相同id的数据合并let newList_(list ).flatten().groupBy(id).map(_.spread((..…

webpack 使用打包报错 ERROR in node_modules\@types\node\ts4.8\assert.d.ts

报错如下&#xff1a; 解决方式&#xff0c;先查看自己的 node 版本 node -v然后再安装 types/node 对应版本&#xff0c;比如我的如下 npm i types/node14.10.0 -D然后再次打包&#xff0c;就没有报错了

SpringBoot项目整合Redis,Rabbitmq发送、消费、存储邮件

&#x1f4d1;前言 本文主要是【Rabbitmq】——SpringBoot项目整合Redis&#xff0c;Rabbitmq发送、消费、存储邮件的文章&#xff0c;如果有什么需要改进的地方还请大佬指出⛺️ &#x1f3ac;作者简介&#xff1a;大家好&#xff0c;我是听风与他&#x1f947; ☁️博客首页…

服务器运行情况及线上排查问题常用命令

一、top命令 指令行&#xff1a; top返回&#xff1a; 返回分为两部分 &#xff08;一&#xff09;系统概览&#xff0c;见图知意 以下是几个需要注意的参数 1、load average&#xff1a; 系统负载&#xff0c;即任务队列的平均长度。三个数值分别为 1分钟、5分钟、15分…

C++基础 -8- 函数重载

函数重载格式(图片代码段呈现) #include "iostream"using namespace std;void rlxy(int a) {cout << "int a"<< endl; }void rlxy(char a) {cout << "char a"<< endl; }int main() {rlxy(99);rlxy(c); }函数重载的依据…

抖音视频如何无水印下载,怎么批量保存主页所有视频没水印?

现在最火的短视频平台莫过于抖音&#xff0c;当我们刷到一个视频想下载下来怎么办&#xff1f;我们知道可以通过保存到相册的方式下载&#xff0c;但用这种方法下载的视频带有水印&#xff0c;而且有些视频不能保存到相册&#xff08;这是视频作者设置了禁止下载&#xff09;。…

中间件安全:JBoss 反序列化命令执行漏洞.(CVE-2017-12149)

中间件安全&#xff1a;JBoss 反序列化命令执行漏洞.&#xff08;CVE-2017-12149&#xff09; JBoss 反序列化漏洞&#xff0c;该漏洞位于 JBoss 的 HttpInvoker 组件中的 ReadOnlyAccessFilter 过滤器中&#xff0c;其 doFilter 方法在没有进行任何安全检查和限制的情况下尝试…