RestTemplate快速开始

本文详细介绍了如何使用Spring Boot的RestTemplate发送HTTPS请求,包括自定义请求工厂处理证书验证,以及如何设置字符编码避免乱码问题。同时,对比了httpclient和okhttp等第三方库在HTTPS请求处理上的优势。
摘要由CSDN通过智能技术生成

RestTemplate快速开始

快速开始

在发送url请求时,使用该工具方便将获取的请求进行映射之类的操作,参数全部放在map对象中,使用HashMap进行封装

xxx xx = restTemplate.getForObject(url,xxx.class[,params])
xxx xx = restTemplate.postForObject(url,xxx.class[,data])
    

HashMap<String, String> map = new HashMap<>();
map.put("id",id);
String json = restTemplate.postForObject("http://abc.com/query",String.class,map)
// 返回json字符串

参考资料:

https://blog.csdn.net/itguangit/article/details/78825505

发送https

restTemplate可以接受一个public RestTemplate(ClientHttpRequestFactory requestFactory)来初始化,可以自定义一个requestFactory类来实现发送https请求:

MySimpleHttpClient.java

public class MySimpleHttpClient extends SimpleClientHttpRequestFactory {

    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        try {
            if (!(connection instanceof HttpsURLConnection)) {
                throw new RuntimeException("需要https的connection");
            }

            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;

            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }

                    }
            };
            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;
        }

        @Override
        public String[] getDefaultCipherSuites() {
            return delegate.getDefaultCipherSuites();
        }

        @Override
        public String[] getSupportedCipherSuites() {
            return delegate.getSupportedCipherSuites();
        }

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

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

        @Override
        public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort) throws
                IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
            return overrideProtocol(underlyingSocket);
        }

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

        @Override
        public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress, final int localPort) throws
                IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
            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;
        }
    }
}

然后初始化restTemplate实例:

RestTemplate https = new RestTemplate(new MySimpleHttpClient());

为了防止乱码,这里设置了字符编码格式:

List<HttpMessageConverter<?>> converterList = https.getMessageConverters();
converterList.remove(1); // 移除原来的转换器
// 设置字符编码为utf-8
HttpMessageConverter<?> converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
converterList.add(1, converter); // 添加新的转换器(注:convert顺序错误会导致失败)
https.setMessageConverters(converterList);

使用方式也很简单,和http一样:

String result = https.getForObject("https://www.baidu.com",String.class);

当然,为了实现https请求,可以使用第三方工具类来实现,比springboot自带的restTemplate更简单高效!

目前比较常用的是:httpclient和okhttp

httpclient

// get 方法
public String getHttps() throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpsGet = new HttpGet("https://www.baidu.com");
    CloseableHttpResponse resp = httpClient.execute(httpsGet);
    String result= EntityUtils.toString(resp.getEntity(),"utf-8");
    resp.close();
    return result;
}
// post 方法
// https://www.cnblogs.com/Mr-Rocker/p/6229652.html
// https://www.cnblogs.com/ncy1/p/10668332.html

okhttp:该部分内容过多,单独开一文写_

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值