欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RestTemplate发送HTTPS请求。

程序员文章站 2022-06-24 22:30:50
...

如果您的jdk是1.6或者1.7版本,请先看我的另一篇博客:https://blog.csdn.net/weixin_40723540/article/details/104652593

工具类

package com.pj.acl.interceptor;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
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.SocketException;
import java.security.cert.X509Certificate;
 
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
        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 java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                        @Override
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }
                        @Override
                        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);
            httpsConnection.setFollowRedirects(false);
            httpsConnection.setInstanceFollowRedirects(false);
            httpsConnection.setReadTimeout(5000);
            httpsConnection.setConnectTimeout(10000);
        } 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(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");
            }
            //enabledProtocols里面包含了当前jdk支持的SSL/TLS协议版本
            String[] enabledProtocols = ((SSLSocket) socket).getEnabledProtocols();
            //((SSLSocket) socket).setEnabledProtocols(new String[]{"SSLv3"});
            ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1"});
            try {
				socket.setSoTimeout(500);
			} catch (SocketException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return socket;
        }
    }
}

调用实例:

package com.pj.acl.interceptor;

import java.net.URI;

public class RestTemplateTest {


	public static ResponseEntity<?> exchange(HttpMethod method, String url, String params, HttpHeaders headers, Class<?> responseType) {
		ResponseEntity<?> result = null;
		HttpEntity<String> httpEntity;
		RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
		headers = headers == null ? new HttpHeaders() : headers;
		headers.remove("Content-Length");
		httpEntity = new HttpEntity<String>(params, headers);
		try {
			UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
			URI uri = new URI(builder.build().encode().toString());
			result = restTemplate.exchange(uri, method, httpEntity, responseType);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	public static void main(String args[]){
		try {
			String requestDMS = RestTemplateTest.requestDMS("https://192.168.2.223/wms", null, HttpMethod.GET, 0);
			//String requestDMS = RestTemplateTest.requestDMS("https://www.baidu.com/", null, HttpMethod.GET, 0);
			System.out.println(requestDMS);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static String requestDMS(String url,String params,HttpMethod method,int t) throws Exception{
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8;text/html;");
		headers.setConnection("keep-alive");
		headers.add("Referrer", "no-referrer-when-downgrade");
		headers.add("host", "dms.tdyh.cn");
		URI uri = new URI("https://dms.tdyh.cn");
		headers.setLocation(uri);
		headers.add("content-length", "413");
		headers.add("server", "Microsoft-IIS/10.0");
		return (String) RestTemplateTest.exchange(method, url, params,headers, String.class).getBody();
	}

}

 

相关标签: http