RestTemplate快速開始

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:該部分內容過多,單獨開一文寫_

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章