RestTemple发送https请求

该代码示例展示了如何利用Spring的RestTemplate发送HTTPS请求,特别是在处理文件上传时。通过自定义SimpleClientHttpRequestFactory和TrustManager,允许不验证服务器证书,以实现不受限制的HTTPS连接。同时,创建了一个MyCustomSSLSocketFactory来设置TLS协议版本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用RestTemple,发送https请求


    @RequestMapping("/test")
    public void upload(MultipartFile file) {
         // 重写SimpleClientHttpRequestFactory
        RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        FileSystemResource resource = new FileSystemResource(new File("E://1/png"));
        multiValueMap.add("file", resource);
        String url = "http://";
        //ParameterizedTypeReference 直接返回包装好的对象
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, (HttpEntity<?>) multiValueMap, new ParameterizedTypeReference<String>() {
        });
        // 调用接口返回结果
        String body = responseEntity.getBody();

    }
package org.example.test;

import org.springframework.http.client.SimpleClientHttpRequestFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        try {
            if (!(connection instanceof HttpsURLConnection)) {
                throw new RuntimeException("An instance of HttpsURLConnection is expected");
            }
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
            httpsConnection.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            super.prepareConnection(httpsConnection, httpMethod);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class MyCustomSSLSocketFactory extends SSLSocketFactory {

        private final SSLSocketFactory delegate;

        public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
            this.delegate = delegate;
        }

        /**
         * 返回默认启用的密码套件,除非一个列表启用,对ssl连接的握手会使用这些密码套件
         * 这些默认的服务的最低质量要求保密保护和服务器身份验证
         */
        @Override
        public String[] getDefaultCipherSuites() {
            return delegate.getDefaultCipherSuites();
        }

        /**
         * 返回的密码套件可用于ssl连接启用的名字
         */
        @Override
        public String[] getSupportedCipherSuites() {
            return delegate.getSupportedCipherSuites();
        }

        @Override
        public Socket createSocket(Socket socket, String s, int i, boolean b) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(socket, s, i, b);
            return overrideProtocol(underlyingSocket);
        }

        @Override
        public Socket createSocket(String s, int i) throws IOException, UnknownHostException {
            final Socket underlyingSocket = delegate.createSocket(s, i);
            return overrideProtocol(underlyingSocket);
        }

        @Override
        public Socket createSocket(String s, int i, InetAddress inetAddress, int i1) throws IOException, UnknownHostException {
            final Socket underlyingSocket = delegate.createSocket(s, i, inetAddress, i1);
            return overrideProtocol(underlyingSocket);
        }

        @Override
        public Socket createSocket(InetAddress inetAddress, int i) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(inetAddress, i);
            return overrideProtocol(underlyingSocket);
        }

        @Override
        public Socket createSocket(InetAddress inetAddress, int i, InetAddress inetAddress1, int i1) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(inetAddress, i, inetAddress1, i1);
            return overrideProtocol(underlyingSocket);
        }

        private Socket overrideProtocol(final Socket socket) {
            if (!(socket instanceof SSLSocket)) {
                throw new RuntimeException("An instance of SSLSocket is expected");
            }
            ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1"});
            return socket;
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值