一。导入依赖

pom.xml

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

二。springboot引入配置


package com.jztey.gxdemo; import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.List; import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate; @Configuration
public class RestConfiguration { @Bean @ConditionalOnMissingBean({RestOperations.class, RestTemplate.class}) public RestOperations restOperations() { //        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); 
//        requestFactory.setReadTimeout(5000); 
//        requestFactory.setConnectTimeout(5000); CloseableHttpClient httpClient = null; try { httpClient = HttpClientUtils.acceptsUntrustedCertsHttpClient(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory); // 使用 utf-8 编码集的 conver 替换默认的 conver(默认的 string conver 的编码集为 "ISO-8859-1") List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters(); Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator(); while (iterator.hasNext()) { HttpMessageConverter<?> converter = iterator.next(); if (converter instanceof StringHttpMessageConverter) { iterator.remove(); } } messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8"))); return restTemplate; }
}

由于需要支持https 需要自定义httpclient  注入

package com.jztey.gxdemo; 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.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; /** * Created by Administrator on 2015/6/8. */
public class HttpClientUtils { public static CloseableHttpClient acceptsUntrustedCertsHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { HttpClientBuilder b = HttpClientBuilder.create(); // setup a Trust Strategy that allows all certificates. // SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); b.setSSLContext(sslContext); // don't check Hostnames, either. //      -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; // here's the special part: //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy"; //      -- and create a Registry, to register it. // SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory) .build(); // now, we create connection-manager using our Registry. //      -- allows multi-threaded use PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry); connMgr.setMaxTotal(200); connMgr.setDefaultMaxPerRoute(100); b.setConnectionManager( connMgr); // finally, build the HttpClient; //      -- done! CloseableHttpClient client = b.build(); return client; } }

三.使用

    @Autowired private RestOperations restOperations;

    @Test public void testHttpGet(){ String url = "https://internal.api.ehaoyao.com/logistics/v1.1/company"; OauthParam param = new OauthParam(); param.setGrantType("client_credentials"); param.setClientId("02bceec105cd4462b2dadd892fdba943"); param.setClientSecret("fa50ffdbbbf9442f8958e1493e7a1b41"); param.setScope("mall"); String token = oauthService.getToken(param); url=url+"?access_token="+token; Map<String,Object> uriVariables = new HashMap<String,Object>(); uriVariables.put("access_token", token); JSONArray result =  restOperations.getForObject(url, JSONArray.class); System.out.println(result.toString()); }

--------------

学习视频

复制链接,在浏览器打开
tomcat源码解析
https://study.163.com/course/introduction/1209535854.htm

Springmvc源码解析
https://study.163.com/course/introduction/1209536851.htm

dubbo源码解析
https://study.163.com/course/introduction/1209648816.htm

源码悟道tomcat+springmvc解析
https://study.163.com/course/introduction/1209399899.htm

springboot中使用RestTemplate相关推荐

  1. Spring Boot项目中使用RestTemplate时出现乱码时的解决方案

    问题描述:SpringBoot项目中使用RestTemplate调用接口时,返回结果中可能会出现以下的乱码现象 解决方法:将返回的结果response.getBody()转换为utf-8格式 Resp ...

  2. 在SpringBoot中使用Spring Session解决分布式会话共享问题

    在SpringBoot中使用Spring Session解决分布式会话共享问题 问题描述: 每次当重启服务器时,都会导致会员平台中已登录的用户掉线.这是因为每个用户的会话信息及状态都是由session ...

  3. SpringBoot 中 JPA 的使用

    前言 第一次使用 Spring JPA 的时候,感觉这东西简直就是神器,几乎不需要写什么关于数据库访问的代码一个基本的 CURD 的功能就出来了.下面我们就用一个例子来讲述以下 JPA 使用的基本操作 ...

  4. 难以想象SpringBoot中的条件注解底层居然是这样实现的

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 来源 | https://urlify.cn/bm2qqi Spr ...

  5. 面试:SpringBoot中的条件注解底层是如何实现的?

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 来源 | https://urlify.cn/bm2qqi Spr ...

  6. springboot yml怎么建常量_【Java】SpringBoot 中从application.yml中获取自定义常量

    由于这里我想通过java连接linux,connection连接需要host.port.username.password及其他路径等等.不想每次修改的时候都去改源文件,所以想写在applicatio ...

  7. Springboot中给图片添加文字水印

    Springboot中给图片添加文字水印 工作中遇到给图片添加文字水印的需求,记录下来方便之后查阅 需求内容: 给一张图片添加指定文字水印,使一张图片上有多个水印内容,并且设定一个水印开关,可指定是否 ...

  8. 你知道如何在springboot中使用redis吗

    特别说明:本文针对的是新版 spring boot 2.1.3,其 spring data 依赖为 spring-boot-starter-data-redis,且其默认连接池为 lettuce ​  ...

  9. WebSocket的故事(六)—— Springboot中,实现更灵活的WebSocket

    概述 WebSocket的故事系列计划分五大篇六章,旨在由浅入深的介绍WebSocket以及在Springboot中如何快速构建和使用WebSocket提供的能力.本系列计划包含如下几篇文章: 第一篇 ...

最新文章

  1. python(五)模块
  2. 《openssl 编程》之错误处理
  3. Java程序员从笨鸟到菜鸟之(一百零四)java操作office和pdf文件(二)利用POI实现数据导出excel报表...
  4. 【热修复】Andfix源码分析
  5. Spring事务处理之 编程式事务 和 声明式事务
  6. 关于数据准备时,自动棌番的主键,这一字段数据的注意(IT总结之五)
  7. 问题:html控件中sleect的Option()的用法
  8. SLAM_VIO中的IMU模型
  9. Linux shell__文件操作
  10. 蓝屏代码查询及代码分析
  11. 网上书店管理系统mysql代码_网上书店管理系统数据库 sql sever
  12. MySQL-运维工具 pt-archiver数据归档工具
  13. C语言结构体,共用体所占字节数计算
  14. c语言中的矩阵求逆程序,C语言矩阵求逆
  15. 《JavaSE-第十四章》之文件(一)
  16. 7-1 愿天下有情人都是失散多年的兄妹 --DFS
  17. 学奥数对孩子究竟有哪些好处?
  18. 论开展线上业务的纯粹度的重要性
  19. 如何拆宏碁(acer)笔记本--个人动手更换风扇、清理灰尘
  20. 一年省一,两年国集,高二斩获世界金牌,他有哪些经验值得借鉴?

热门文章

  1. 人体存在感应微波雷达模组,静止存在雷达感应技术
  2. mysql dbuild_config_MYSQL5.5源码编译配置选项
  3. 补充准NEUQer充实的一天的打表文件
  4. 第八期 RT3052F芯片分析 《路由器就是开发板》
  5. C语言:用指针比较三个数大小
  6. HGAME 2020 week1
  7. -Djava.endorsed.dirs=D:\Tomcat\apache-tomcat-7.0.86\endorsed is not supported. Endorsed standards an
  8. “运动”主题创作——手绘与码绘的比较
  9. js已知斜率和一点求方程
  10. POST 调用 301 Moved Permanently 问题