写作时间:2018-12-28
Spring Boot: 2.1 ,JDK: 1.8, IDE: IntelliJ IDEA,

说明

截至2018年6月,Alexa排名前100万的网站中有34.6%使用HTTPS作为默认值[1],互联网141387个最受欢迎网站的43.1%具有安全实施的HTTPS[2],以及45%的页面加载(透过Firefox纪录)使用HTTPS[3]。2017年3月,中国注册域名总数的0.11%使用HTTPS。[4]

超文本传输安全协议(英语:Hypertext Transfer Protocol Secure,缩写:HTTPS,常称为HTTP over TLS,HTTP over SSL或HTTP Secure)是一种透过计算机网络进行安全通信的传输协议。HTTPS经由HTTP进行通信,但利用SSL/TLS来加密数据包。HTTPS开发的主要目的,是提供对网站服务器的身份认证,保护交换数据的隐私与完整性。这个协议由网景公司(Netscape)在1994年首次提出,随后扩展到互联网上。
以上内容来自维基百科。

本文主要说明用RestTemplate请求HTTPS。搜索引擎搜索的时候请求用的是Spring Boot https Client; 默认搜索结果Spring Boot https Server。

获取天气预报api

为了测试HTTPS,先找一个免费的天气预报资源:

  1. 打开和风网站,网址是这个https://www.heweather.com,然后注册账号,找到自己的KEY,再打开这个API说明。https://www.heweather.com/documents/api/s6/weather-forecast

    得出测试链接格式为:
https://free-api.heweather.net/s6/weather/forecast?location=$&key=$
  1. 在网址http://www.weather.com.cn/weather/101280101.shtml找到城市的天气预报,这里以广州为例,最后得出的测试链接为
https://free-api.heweather.net/s6/weather/forecast?location=CN101280101&key=34a265026b544eac9b3dcd9f104a7bb6

网页请求结果

{"HeWeather6":[{"basic": {"cid":"CN101280101","location":"广州","parent_city":"广州","admin_area":"广东","cnty":"中国","lat":"23.12517738","lon":"113.28063965","tz":"+8.00"},"update":{"loc":"2018-12-28 20:57","utc":"2018-12-28 12:57"},"status":"ok","daily_forecast":[{"cond_code_d":"101","cond_code_n":"104","cond_txt_d":"多云","cond_txt_n":"阴","date":"2018-12-28","hum":"58","mr":"23:47","ms":"11:44","pcpn":"5.0","pop":"80","pres":"1024","sr":"07:07","ss":"17:50","tmp_max":"17","tmp_min":"7","uv_index":"0","vis":"10","wind_deg":"359","wind_dir":"北风","wind_sc":"4-5","wind_spd":"28"},{"cond_code_d":"104","cond_code_n":"104","cond_txt_d":"阴","cond_txt_n":"阴","date":"2018-12-29","hum":"53","mr":"00:00","ms":"12:25","pcpn":"1.0","pop":"56","pres":"1028","sr":"07:07","ss":"17:51","tmp_max":"12","tmp_min":"5","uv_index":"1","vis":"20","wind_deg":"6","wind_dir":"北风","wind_sc":"4-5","wind_spd":"27"},{"cond_code_d":"104","cond_code_n":"305","cond_txt_d":"阴","cond_txt_n":"小雨","date":"2018-12-30","hum":"41","mr":"00:45","ms":"13:04","pcpn":"5.0","pop":"80","pres":"1029","sr":"07:07","ss":"17:52","tmp_max":"11","tmp_min":"5","uv_index":"1","vis":"20","wind_deg":"0","wind_dir":"北风","wind_sc":"4-5","wind_spd":"26"}]}]
}

工程建立

参照教程【SpringBoot 2.1 | 第一篇:构建第一个SpringBoot工程】新建一个Spring Boot项目,名字叫demoresttemplatehttps, 在目录src/main/java/resources 下找到配置文件application.properties,重命名为application.yml

pom引入httpclient依赖

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

新建RestTemplate配置类

配置可以通过注解 @Configuration ,全局获取。根据最小适用原则,建立配置类com.zgpeace.demoresttemplatehttps.config.RestTemplateConfig
实现代码有注释掉的部分,暂时用不到,后面会说明。

package com.zgpeace.demoresttemplatehttps.config;//import org.apache.http.auth.AuthScope;
//import org.apache.http.auth.UsernamePasswordCredentials;
//import org.apache.http.client.CredentialsProvider;
//import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
//import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
//import org.apache.http.impl.client.BasicCredentialsProvider;
//import org.apache.http.ssl.SSLContextBuilder;import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;@Configuration
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {// unable to find valid certification path to requested target/*SSLContextBuilder builder = new SSLContextBuilder();builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);*/// 401 Unauthorized/*String host = "localhttps";int port = 23333;String user = "john";String password = "123456";CredentialsProvider credsProvider = new BasicCredentialsProvider();credsProvider.setCredentials(new AuthScope(host, port),new UsernamePasswordCredentials(user, password));*/CloseableHttpClient httpClient= HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier())
//                .setSSLSocketFactory(sslConnectionSocketFactory)
//                .setDefaultCredentialsProvider(credsProvider).build();HttpComponentsClientHttpRequestFactory requestFactory= new HttpComponentsClientHttpRequestFactory();requestFactory.setHttpClient(httpClient);RestTemplate restTemplate = new RestTemplate(requestFactory);return restTemplate;}
}

调用接口

完善类 com.zgpeace.demoresttemplatehttps.DemoresttemplatehttpsApplication

package com.zgpeace.demoresttemplatehttps;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;@SpringBootApplication
public class DemoresttemplatehttpsApplication {@AutowiredRestTemplate restTemplate;public static void main(String[] args) {SpringApplication.run(DemoresttemplatehttpsApplication.class, args);}@Beanpublic CommandLineRunner run() throws Exception {return args -> {String url = "https://free-api.heweather.net/s6/weather/forecast?location=CN101280101&key=34a265026b544eac9b3dcd9f104a7bb6";ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);String body = responseEntity.getBody();System.out.println("body --> " + body);};}
}

通过 @Autowire 注入restTemplate对象。

证书无效的网站

证书无效的网站,请求会报错unable to find valid certification path to requested target ,解决方案如下:

// unable to find valid certification path to requested targetSSLContextBuilder builder = new SSLContextBuilder();builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);CloseableHttpClient httpClient= HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).setSSLSocketFactory(sslConnectionSocketFactory)
//                .setDefaultCredentialsProvider(credsProvider).build();

需要授权登录的网站

需要授权登录的网站,需要用户名密码,如下图演示:

解决方案如下:

// 401 UnauthorizedString host = "localhttps";int port = 23333;String user = "john";String password = "123456";CredentialsProvider credsProvider = new BasicCredentialsProvider();credsProvider.setCredentials(new AuthScope(host, port),new UsernamePasswordCredentials(user, password));CloseableHttpClient httpClient= HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier())
//                .setSSLSocketFactory(sslConnectionSocketFactory).setDefaultCredentialsProvider(credsProvider).build();

控制台打印日志:

body --> {"HeWeather6":[{"basic":{"cid":"CN101280101","location":"广州","parent_city":"广州","admin_area":"广东","cnty":"中国","lat":"23.12517738","lon":"113.28063965","tz":"+8.00"},"update":{"loc":"2018-12-28 21:57","utc":"2018-12-28 13:57"},"status":"ok","daily_forecast":[{"cond_code_d":"101","cond_code_n":"104","cond_txt_d":"多云","cond_txt_n":"阴","date":"2018-12-28","hum":"58","mr":"23:47","ms":"11:44","pcpn":"5.0","pop":"80","pres":"1024","sr":"07:07","ss":"17:50","tmp_max":"17","tmp_min":"7","uv_index":"0","vis":"10","wind_deg":"9","wind_dir":"北风","wind_sc":"4-5","wind_spd":"31"},{"cond_code_d":"104","cond_code_n":"104","cond_txt_d":"阴","cond_txt_n":"阴","date":"2018-12-29","hum":"53","mr":"00:00","ms":"12:25","pcpn":"1.0","pop":"56","pres":"1028","sr":"07:07","ss":"17:51","tmp_max":"12","tmp_min":"5","uv_index":"1","vis":"20","wind_deg":"359","wind_dir":"北风","wind_sc":"4-5","wind_spd":"30"},{"cond_code_d":"104","cond_code_n":"305","cond_txt_d":"阴","cond_txt_n":"小雨","date":"2018-12-30","hum":"41","mr":"00:45","ms":"13:04","pcpn":"5.0","pop":"80","pres":"1029","sr":"07:07","ss":"17:52","tmp_max":"11","tmp_min":"5","uv_index":"1","vis":"20","wind_deg":"9","wind_dir":"北风","wind_sc":"4-5","wind_spd":"26"}]}]
}

总结

恭喜你!学会了RestTemplate请求https。
代码下载:https://github.com/zgpeace/Spring-Boot2.1/tree/master/http/demoresttemplatehttps

参考:
http://www.rain1024.com/2017/04/26/api-article76/
http://www.tutorialsteacher.com/https/what-is-https
https://developers.google.com/web/fundamentals/security/encrypt-in-transit/why-https
https://zh.wikipedia.org/wiki/%E8%B6%85%E6%96%87%E6%9C%AC%E4%BC%A0%E8%BE%93%E5%AE%89%E5%85%A8%E5%8D%8F%E8%AE%AE
https://o7planning.org/en/11649/secure-spring-boot-restful-service-using-basic-authentication

易筋SpringBoot 2.1 | 第五篇:RestTemplate请求https(3)相关推荐

  1. python实训心得2000_实训总结万能版2000字五篇

    实训总结万能版 2000 字五篇 通过这次实训,我收获了很多,一方面学习到了许多以前没 学过的专业知识与知识的应用,另一方面还提高了自己动手做项 目的能力. 本次实训, 是对我能力的进一步锻炼, 也是 ...

  2. Python之路【第五篇】:面向对象及相关

    Python之路[第五篇]:面向对象及相关 Python之路[第五篇]:面向对象及相关 面向对象基础 基础内容介绍详见一下两篇博文: 面向对象初级篇 面向对象进阶篇 其他相关 一.isinstance ...

  3. 第五篇:Visual Studio 2008 Web开发使用的新特性

    第五篇:Visual Studio 2008 Web开发使用的新特性 本篇翻译自MSDN. .NET Framwork 3.5与Visual Studio 2008 包含很多新特性.AJAX的Web开 ...

  4. OpenCV学习系列教程第五篇:测试和提高代码的效率

    Opencv-Python学习系列教程第五篇 来自opencv-python官方学习文档,本人谨做翻译和注释,以及一些自己的理解 本文由作者翻译并进行代码验证,转载请注明出处~ 官方文档请参阅:htt ...

  5. 带你少走弯路:五篇文章学完吴恩达机器学习

    本文是吴恩达老师的机器学习课程[1]的笔记和代码复现部分,这门课是经典,没有之一.但是有个问题,就是内容较多,有些内容确实有点过时. 如何在最短时间学完这门课程?作为课程的主要翻译者和笔记作者,我推荐 ...

  6. 坚持的力量 第十五篇

    第十五篇        漩涡鸣人 从他身上,我看到了进步和向上的力量,经别人推荐,我发现我渐渐的喜欢上了<火影忍者>. 首先,<火影>中的歌曲很有震撼力和穿透力,产生心灵的共鸣 ...

  7. 【OpenCV入门指南】第五篇轮廓检测 下

    上一篇<[OpenCV入门指南]第五篇轮廓检测上>介绍了cvFindContours函数和cvDrawContours函数,并作了一个简单的使用示范.本篇将展示一个实例,让大家对轮廓检测有 ...

  8. 推荐五篇论文| 轻量级的Transformer; 对比学习;ResNeSt;Shortcut Learning等

    本文介绍了最近比较有意思的五篇文章: 轻量级的transformer 监督式的对比学习 shortcur learning ResNeSt Attention模块的分析 Lite Transforme ...

  9. 史上最简单的SpringCloud教程 | 第五篇: 路由网关(zuul)

    转:https://blog.csdn.net/forezp/article/details/69939114 最新版本: 史上最简单的SpringCloud教程 | 第五篇: 路由网关(zuul)( ...

  10. 【Python五篇慢慢弹】数据结构看python

    数据结构看python 作者:白宁超 2016年10月9日14:04:47 摘要:继<快速上手学python>一文之后,笔者又将python官方文档认真学习下.官方给出的pythondoc ...

最新文章

  1. android 8.0 l2tp问题,【Win】使用L2TP出現809錯誤
  2. struts文件上传
  3. python和docker交互_jupyter notebook 连接服务器docker中python环境
  4. 大山深处,有一所希望学校
  5. 【收藏】gitee:使用k8s部署nacos
  6. 移动互联网与传统互联网体验上的区别及功能测试要点(总结自《大话移动APP测试》)...
  7. 六年级下计算机课ppt课件ppt课件,信息技术六年级《第7课 机器人沿线行走》ppt课件(苏科版)...
  8. 前端性能优化:Add Expires headers
  9. Qt——P13 Q4版本信号槽连接
  10. 构造函数与new关键字
  11. Material UI 4.10 Skeleton 骨架
  12. 人脸检测(三)--Haar特征原理及实现
  13. android移动商城源码,o2o移动社区Android端app开源源码
  14. Telink RDS IDE编译问题
  15. 【阿里云产品使用教程】1. 阿里云VPC ECS SLB NAT初体验 - 上
  16. 研究生必须过计算机和英语吗,2020考研:英语一75分,她是怎么做到的_计算机考研科目...
  17. 读《Python编程:从入门到实践》
  18. csol控制台+去黑雾
  19. Mybatis-9.28
  20. 西工大NOJ数据结构理论——013.以十字链表为存储结构实现矩阵相加(严5.27)

热门文章

  1. angular自带的一些api_在Angular软件中执行API请求的正确方式,了解一下
  2. 如何循序渐进向DotNet架构师发展(转)
  3. 如何使用华为官方模拟器eNSP的12800为后续SDN实验做好准备
  4. 【跃迁之路】【586天】程序员高效学习方法论探索系列(实验阶段343-2018.09.14)...
  5. 贵阳打出大数据战略组合拳
  6. 设计模式之Interpreter(解释器)
  7. 生成一定范围内的互不相同的随机数的方法比较
  8. IIS6上传文件尺寸太小解决办法
  9. SpringBoot的C2C水果商城系统
  10. sql server根据年查询日期_SQL根据日期条件使用between查询数据集应注意事项