1. ホーム
  2. Java

java send https request prompt java.security.cert.について。

2022-02-12 19:43:32
<パス

1. この2日間はプロジェクトで外部インターフェースを呼び出す必要があり、最初は至って簡単だと思っていたのですが、HttpConnectionを使用してpostリクエストを送信する際に以下のエラーメッセージが表示されました。ログのエラーメッセージを見ると、HttpConnectionへのhttp接続を作成する際にSSLセキュリティ認証に問題があり、関連情報を調べてみると、外部インターフェースのhttps証明書のホスト名とローカルのhttpsリクエストのホスト名に矛盾があることが原因でした。 アドレスアクセスは安全ではない、これは個人認証用のサーバー側の証明書が原因であるはずです。

HttpException: java.security.cert.CertificateException: No name matching nyq.esgcc.com.cn found; <--- java.security.cert. CertificateException: No name matching nyq.esgcc.com.cn found
	at jodd.http.net.SocketHttpConnectionProvider.createHttpConnection(SocketHttpConnectionProvider.java:101) ~[ SocketHttpConnectionProvider.class:?]
	at jodd.http.HttpRequest.open(HttpRequest.java:737) ~[ HttpRequest.class:?]
	at jodd.http.HttpRequest.open(HttpRequest.java:721) ~[HttpRequest.class:?]
	at jodd.http.HttpRequest._send(HttpRequest.java:819) ~[HttpRequest.class:?]
	at jodd.http.HttpRequest.send(HttpRequest.java:814) ~[HttpRequest.class:?]
	at com.bxd.core.util.HttpUtil.post(HttpUtil.java:126) ~[HttpUtil.class:?]
	at com.bxd.core.util.HttpUtil.post(HttpUtil.java:102) ~[HttpUtil.class:?]
	at com.bxd.app.controller.TestController.forward(TestController.java:73) ~[TestController.class:?]
	at com.bxd.app.controller.TestController$$FastClassBySpringCGLIB$$a0caf4a6.invoke(<generated>) ~[TestController.class:?]
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[MethodProxy.class:4.3.9.RELEASE]
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738) ~[CglibAopProxy$ CglibMethodInvocation.class:4.3.9.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[ ReflectiveMethodInvocation.class:4.3.9.RELEASE]
	at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52) ~[ MethodBeforeAdviceInterceptor.class:4.3.9.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[ ReflectiveMethodInvocation.class:4.3.9.RELEASE]
	at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52) ~[ AfterReturningAdviceInterceptor.class:4.3.9.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[ ReflectiveMethodInvocation.class:4.3.9.RELEASE]
	at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[ ExposeInvocationInterceptor.class:4.3.9.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[ ReflectiveMethodInvocation.class:4.3.9.RELEASE]
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673) ~[CglibAopProxy$ DynamicAdvisedInterceptor.class:4.3.9.RELEASE]
	at com.bxd.app.controller.TestController$$EnhancerBySpringCGLIB$$e08ed4b.forward(<generated>) ~[TestController.class:?]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[? :1.8.0_102]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[? :1.8.0_102]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[? :1.8.0_102]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[? :1.8.0_102]
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:20
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.14]
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat-websocket.jar:8.0.14]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.14]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.14]
	at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:123) [WebStatFilter.class:1.0.29]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.14]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.14]
	at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:209) [CORSFilter.class:2.6]
	at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:244) [CORSFilter.class:2.6]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.14]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.14]
	at com.bxd.core.filter.XssFilter.doFilter(XssFilter.java:45) [XssFilter.class:?]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.14]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.14]
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) [ CharacterEncodingFilter.class:4.3.9.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [OncePerRequestFilter.class:4.3.9. RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) [catalina.jar:8.0.14]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:8.0.14]
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) [catalina.jar:8.0.14]
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) [catalina.jar:8.0.14]
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506) [catalina.jar:8.0.14]
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) [catalina.jar:8.0.14]
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) [catalina.jar:8.0.14]
	at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:676) [catalina.jar:8.0.14]
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610) [catalina.jar:8.0.14]
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) [catalina.jar:8.0.14]
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537) [catalina.jar:8.0.14]
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081) [tomcat-coyote.jar:8.0.14]
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658) [tomcat-coyote.jar:8.0.14]
	at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277) [tomcat-coyote.jar:8.0.14]
	at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403) [tomcat-coyote.jar:8.0.14]
	at org.apache.tomc

2. ここでは、解決策は、まず、すべての、情報を見つけるために、インターネットは、何も有用な見つけることが判明し、うっかり次の友人に尋ねた、証明書の検出をバイパスするためにhttpsの要求を送信するための実現可能な方法を発見した。以下のコードが添付されていますので、必要であれば試してみてください。 doget メソッドを呼び出すだけ このコードでは、https リクエストが含まれているかどうかを判断し、含まれている場合は、静的メソッド sendSSLPostMethod の ignoreHostnameVerifier を使用して、証明書の hostName を無視します(これが鍵になるはずです)。これにより、hostName と証明書の hostname の間に矛盾が生じ、マッチしないリクエストが発生する問題を回避することができます。

package bxdweb;

import java.io;
import java.io;
import java.io;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

 
/**
 */
public class HttpTookit {
	private static Logger logger = LoggerFactory.getLogger(HttpTookit.class);
    private static final CloseableHttpClient httpClient;
    public static final String CHARSET = "UTF-8";
 
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(300000).setSocketTimeout(300000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }
 
    public static String doGet(String url, Map<String, Object> params){
    	
    	if(isHttps(url)){
    		returnSSLPostMethod(url, params);
    	}
    	else{
    		return doGet(url, params,CHARSET);
    	}
    	
        
    }
    public static String doPost(String url, Map<String, Object> params){
        return doPost(url, params,CHARSET);
    }
    /**
     * HTTP Get Get the content
     * @param url The url address of the request ? The previous ground �?
     * @param params Parameters of the request
     * @param charset Encoding format
     * @return page content
     */
    public static String doGet(String url,Map<String,Object> params,String charset){
        if(StringUtils.isBlank(url)){
            return null;
        }
        HttpGet httpGet = null;
        try {
            if(params ! = null && !params.isEmpty()){
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for(Map.Entry<String,Object> entry : params.entrySet()){
                    if(entry.getValue() ! = null){
                        pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
                    }
                }
                url += "? " + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }
            logger.info("=======HttpTookit request url address: "+url+"==========");
            httpGet = new HttpGet(url);
            CloseableHttpResponse response = ht
        if (null == paramToMap || paramToMap.isEmpty()) {
            return null;
        }
        StringBuffer url = new StringBuffer();
        boolean isfist = true;
        for (Entry<String, Object> entry : paramToMap.entrySet()) {
            if (isfist) {
                isfist = false;
            } else {
                url.append("&");
            }
            url.append(entry.getKey()).append("=");
            String value = entry.getValue().toString();
            if (!StringUtils.isEmpty(value)) {
                url.append(URLEncoder.encode(value, CHARSET));
            }
        }
        return url.toString();
    }

    /**
     * Check if https
     * 
     * @param url
     */
    protected static boolean isHttps(String url) {
        return url.startsWith("https");
    }

    /**
     * https domain checksum
     * 
     * @param url
     * @param params
     * @return
     */
    public static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;// return true directly
        }
    }
    
    
    public static class MyX509TrustManager implements X509TrustManager {

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}  
    	  
       
      
    }  
    
    
    
    
	/**
     * Ignore the certificate HostName
     */
    private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String s, SSLSession sslsession) {
            System.out.println("WARNING: Hostname is not matched for cert.");
            return true;
        }
    };

    /**
     * Ignore Certification
     */
    private static TrustManager ignoreCertificationTrustManger = new X509TrustManager(){
        private X509Certificate[] certificates;
        public void checkClientTrusted(X509Certificate certificates[],
                                       String authType) throws CertificateException {
            if (this.certificates == null) {
                this.certificates = certificates;
            }
        }
        public void checkServerTrusted(X509Certificate[] ax509certificate,
                                       String s) throws CertificateException {
            if (this.certificates == null) {
                this.certificates = ax509certificate;
            }
        }
        public X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[0];
        }
    };

    public static String sendSSLGetMethod(String urlString) throws Exception{
        String repString = null;
        InputStream is = null;
        HttpsURLConnection connection = null;
        try {

            URL url = new URL(urlString);
            /*
             * use ignore host name verifier
             */
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            connection = (HttpsURLConnection) url.openConnection();
            // Prepare SSL Context
            TrustManager[] tm = { ignoreCertificationTrustManger };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());

            // Get the SSLSocketFactory object from the above SSLContext object
            SSLSocketFactory ssf =

情報提供ありがとうございました。 参考アドレス