REST访问(RestTemplate)
https://www.cnblogs.com/softidea/p/6910198.html
经常需要发送一个GET/POST请求到其他系统(REST API),通过JDK自带的HttpURLConnection、Apache HttpClient、Netty 4、OkHTTP 2/3都可以实现。
HttpClient的使用:http://rensanning.iteye.com/blog/1550436
Spring的RestTemplate封装了这些库的实现,使用起来更简洁。
RestTemplate包含以下几个部分:
HttpMessageConverter 对象转换器
ClientHttpRequestFactory 默认是JDK的HttpURLConnection
ResponseErrorHandler 异常处理
ClientHttpRequestInterceptor 请求拦截器
@Service
public class AccountService { @Autowired
private RestTemplate restTemplate; // ... }
(1)发送GET请求(getForObject()、getForEntity()、exchange())
// 1-getForObject()
User user1 = this.restTemplate.getForObject(uri, User.class); // 2-getForEntity()
ResponseEntity<User> responseEntity1 = this.restTemplate.getForEntity(uri, User.class);
HttpStatus statusCode = responseEntity1.getStatusCode();
HttpHeaders header = responseEntity1.getHeaders();
User user2 = responseEntity1.getBody(); // 3-exchange()
RequestEntity requestEntity = RequestEntity.get(new URI(uri)).build();
ResponseEntity<User> responseEntity2 = this.restTemplate.exchange(requestEntity, User.class);
User user3 = responseEntity2.getBody();
(2)发送POST请求(postForObject()、postForEntity()、exchange())
// 1-postForObject()
User user1 = this.restTemplate.postForObject(uri, user, User.class); // 2-postForEntity()
ResponseEntity<User> responseEntity1 = this.restTemplate.postForEntity(uri, user, User.class); // 3-exchange()
RequestEntity<User> requestEntity = RequestEntity.post(new URI(uri)).body(user);
ResponseEntity<User> responseEntity2 = this.restTemplate.exchange(requestEntity, User.class);
(3)设置HTTP Header信息
// 1-Content-Type
RequestEntity<User> requestEntity = RequestEntity
.post(new URI(uri))
.contentType(MediaType.APPLICATION_JSON)
.body(user); // 2-Accept
RequestEntity<User> requestEntity = RequestEntity
.post(new URI(uri))
.accept(MediaType.APPLICATION_JSON)
.body(user); // 3-Other
RequestEntity<User> requestEntity = RequestEntity
.post(new URI(uri))
.header("Authorization", "Basic " + base64Credentials)
.body(user);
(4)异常处理
捕获HttpServerErrorException
int retryCount = 0;
while (true) {
try {
responseEntity = restTemplate.exchange(requestEntity, String.class);
break;
} catch (HttpServerErrorException e) {
if (retryCount == 3) {
throw e;
}
retryCount++;
}
}
自定义异常处理
public class CustomErrorHandler extends DefaultResponseErrorHandler { @Override
public void handleError(ClientHttpResponse response) throws IOException { } }
@Configuration
public class RestClientConfig { @Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new CustomErrorHandler());
return restTemplate;
} }
(5)设置超时时间
@Configuration
public class RestClientConfig { @Bean
public RestTemplate restTemplate() {
return new RestTemplate(clientHttpRequestFactory());
} private ClientHttpRequestFactory clientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setReadTimeout(2000);
factory.setConnectTimeout(2000);
return factory;
}
}
(6)设置连接池
@Configuration
public class RestClientConfig { @Bean
public ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
} @Bean
public RestTemplate restTemplate() {
return new RestTemplate(httpRequestFactory());
} @Bean
public HttpClient httpClient() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(5);
connectionManager.setDefaultMaxPerRoute(5); RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(8000)
.setConnectTimeout(8000)
.setConnectionRequestTimeout(8000)
.build(); return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
.build();
} }
(7)发送文件
MultiValueMap<String, Object> multiPartBody = new LinkedMultiValueMap<>();
multiPartBody.add("file", new ClassPathResource("/tmp/user.txt"));
RequestEntity<MultiValueMap<String, Object>> requestEntity = RequestEntity
.post(uri)
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(multiPartBody);
(8)下载文件
// 小文件
RequestEntity requestEntity = RequestEntity.get(uri).build();
ResponseEntity<byte[]> responseEntity = restTemplate.exchange(requestEntity, byte[].class);
byte[] downloadContent = responseEntity.getBody(); // 大文件
ResponseExtractor<ResponseEntity<File>> responseExtractor = new ResponseExtractor<ResponseEntity<File>>() {
@Override
public ResponseEntity<File> extractData(ClientHttpResponse response) throws IOException {
File rcvFile = File.createTempFile("rcvFile", "zip");
FileCopyUtils.copy(response.getBody(), new FileOutputStream(rcvFile));
return ResponseEntity.status(response.getStatusCode()).headers(response.getHeaders()).body(rcvFile);
}
};
File getFile = this.restTemplate.execute(targetUri, HttpMethod.GET, null, responseExtractor);
(9)Spring Boot的RestTemplateBuilder
全局设置
@Component
public class CustomRestTemplateCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
new RestTemplateBuilder()
.detectRequestFactory(false)
.basicAuthorization("username", "password")
.uriTemplateHandler(new OkHttp3ClientHttpRequestFactory())
.errorHandler(new CustomResponseErrorHandler())
.configure(restTemplate);
}
}
单独设置
@Service
public class MyRestClientService { private RestTemplate restTemplate; public MyRestClientService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder
.basicAuthorization("username", "password")
.setConnectTimeout(3000)
.setReadTimeout(5000)
.rootUri("http://api.example.com/")
.errorHandler(new CustomResponseErrorHandler())
.additionalMessageConverters(new CustomHttpMessageConverter())
.uriTemplateHandler(new OkHttp3ClientHttpRequestFactory())
.build();
} public String site() {
return this.restTemplate.getForObject("http://rensanning.iteye.com/", String.class);
} }
http://rensanning.iteye.com/blog/2362105
REST访问(RestTemplate)的更多相关文章
- Spring Boot REST(一)核心接口
Spring Boot REST(一)核心接口 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html) SpringBoot RE ...
- Spring RestTemplate: 比httpClient更优雅的Restful URL访问, java HttpPost with header
{ "Author": "tomcat and jerry", "url":"http://www.cnblogs.com/tom ...
- restTemplate设置访问超时
(一)RestTemplate 客户端 1.RestTemplate 是Spring的封装,需要spring的包 spring-web-3.0.7.RELEASE.jar 2.客户端代码: /** * ...
- Spring提供的用于访问Rest服务的客户端:RestTemplate实践
什么是RestTemplate? RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效 ...
- Eureka restTemplate访问超时
错误代码 I/O error on GET request for "http://sushibase/v1/Publich/authorize": Connection time ...
- 如何使用RestTemplate访问restful服务
一. 什么是RestTemplate 传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient.不过此种方法使用起来太过繁琐.spring提供了一种简单便捷的模板类 ...
- How to disable SSL certificate checking with Spring RestTemplate?(使用resttemplate访问https时禁用证书检查)
How to disable SSL certificate checking with Spring RestTemplate?(使用resttemplate访问https时禁用证书检查) **** ...
- java之RestTemplate的访问应用
一.REST即表述性状态传递(英文:Representational State Transfer,简称REST)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格.它是 ...
- Httpclient与RestTemplate的比较(比httpClient更优雅的Restful URL访问)
一.HttpClient (一)HttpClient 客户端 1.HttpClient 是 apache 的开源,需要引入两个包:httpclient-4.2.4.jar 和 httpcore-4.2 ...
随机推荐
- 组合数学中的常见定理&组合数的计算&取模
组合数的性质: C(n,m)=C(n,n-m); C(n,m)=n!/(m!(n-m)!); 组合数的递推公式: C(n,m)= C(n-1,m-1)+C(n-1,m); 组合数一般数值较大,题目会 ...
- bootstrap学习大纲
bootstrap 学习分三部分,分别是 css样式,css组件,js插件. 下面介绍三部分分别要学习的内容: 1.css样式:栅格系统,排版,代码,表格,表单,按钮,图片,辅助类,响应式工具. 2. ...
- [SHOI 2017] 组合数问题
[题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=4870 [算法] 回顾组合数的定义 : C(N , M)表示将N个小球放入M个盒子里的 ...
- java-执行dos命令
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOExce ...
- OpenResty创造者
OpenResty 是一个开源的 Web 平台,用于开发高性能和高动态的 Web 网关或者 Web 应用.OpenResty 最早是为了支持全网搜索引擎周边的相关搜索的 API 接口,后来我们基于 N ...
- jni中c代码调用java代码
原理是使用反射的机制 java中反射的例子: Class<?> forName = Class.forName("com.example.ndkcallback.DataProv ...
- windows: Python安装scipy,scikit-image时提示"no lapack/blas resources found"的解决方法
解决方案: 最后,解决我遇到的这个问题的解决方案是来自以下链接的答案: http://www.voidcn.com/blog/z6491679/article/p-5740396.html. 另外还有 ...
- silverlight RadGridView 动态添加数据列
public void BindFaultGridInfo(IList<HealthStatusApp.Web.Models.FaultMajorModel> list) { rg_Fau ...
- UItextFied 的属性
网络学习笔记 在iPhone应用中通过UITextField填写信息时,经常出现出现自动更正输入信息.首字母大写等情况 尤其是在填写用户名时,这种本想提供便捷的功能反而让人感到特别麻烦 今天查了相关书 ...
- 解决 'chromedriver' executable needs to be in PATH.'报错
试了把chromedriver.exe放到chrome安装文件下,python安装文件下,然后把路径配到path里,均无用. 最后是修改函数调用得以解决: from selenium import w ...