使用HttpsURLConnection请求https报错

**背景:**公司需要在搭建的生产应用系统中上传图片文件后,自动调用公司打印机打印,但是生产环境的是外网是无法调用公司内网打印机的,但可以将打印机上云,暂时没有这样子做,所以使用了其他方法,写个jar包持续定时调用外网生产应用系统的https接口请求将图片下载到本地,再调用公司打印机打印。在调用https请求出现异常。

**原因:**使用Java原生HttpsURLConnection去请求https是会缺少证书无法请求成功的,但是请求http可以请求成功。

**解决:**在HttpsURLConnection之前添加以下代码:

java 复制代码
TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                }
        };
       
// 使用信任管理器创建SSL上下文
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

// 以上代码需要在HttpsURLConnection之前添加

//定义一个URL对象,就是你想下载的图片的URL地址
URL url = new URL(fileUrl);
//打开连接
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
//设置请求方式为"GET"
conn.setRequestMethod("GET");
//超时响应时间为10秒
conn.setConnectTimeout(10 * 1000);
//通过输入流获取图片数据
InputStream is = conn.getInputStream();
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
byte[] data = readInputStream(is);
//创建一个文件对象用来保存图片,默认保存当前工程根目录,起名叫Copy.jpg
long timestamp = new Date().getTime();
File imageFile = new File(DOWNLOAD_FILE + timestamp + ".jpg");
System.out.println("本地下载了文件, file" + imageFile.getName());
//创建输出流
FileOutputStream outStream = new FileOutputStream(imageFile);
//写入数据
outStream.write(data);
//关闭输出流,释放资源
outStream.close();
return imageFile;
相关推荐
小涛不学习1 小时前
HTTP 和 HTTPS 详解(原理 + 区别 + 面试重点)
http·面试·https
一直都在5721 小时前
HTTPS 加密传输原理
网络协议·http·https
爱丽_2 小时前
TCP vs UDP 怎么选(偏实战:别背概念,用场景做决策)
网络协议·tcp/ip·udp
虾..2 小时前
Linux HTTP服务器
linux·服务器·http
taxunjishu3 小时前
TCP/IP转EtherNet/IP 协议转换 罗克韦尔PLC与视觉设备交互
网络·网络协议·tcp/ip
yy55273 小时前
Nginx 安全防护与 HTTPS 部署实战
nginx·安全·https
cheems95275 小时前
[网络原理] HTTPS 加密演进与中间人攻击
网络·网络协议·http·https
qq_570398575 小时前
websocket
网络·websocket·网络协议
葡萄城技术团队5 小时前
Hurley:用 Rust 打造的高性能 HTTP 客户端 + 压测工具
开发语言·http·rust
爱丽_6 小时前
HTTPS 与 TLS 握手
网络协议·http·https