2 wlq199101 wlq199101 于 2017.09.05 11:54 提问

Java 访问 Https接口 忽略证书
/**  
 * 证书信任管理器(用于https请求)  
 * @date 2013-08-08  
 */  
public class MyX509TrustManager implements X509TrustManager{  
    public void checkClientTrusted(X509Certificate[] arg0, String arg1)  
            throws CertificateException {  
    }  
    public void checkServerTrusted(X509Certificate[] arg0, String arg1)  
            throws CertificateException {  
    }  
    public X509Certificate[] getAcceptedIssuers() {  
        return null;  
    }  
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {    
        JSONObject jsonObject = null;    
        StringBuffer buffer = new StringBuffer();    
        try {    
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化    
            TrustManager[] tm = { new MyX509TrustManager() };    
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");    
            sslContext.init(null, tm, new java.security.SecureRandom());    
            // 从上述SSLContext对象中得到SSLSocketFactory对象    
            SSLSocketFactory ssf = sslContext.getSocketFactory();    

            URL url = new URL(requestUrl);    
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();    
            httpUrlConn.setSSLSocketFactory(ssf);    

            httpUrlConn.setDoOutput(true);    
            httpUrlConn.setDoInput(true);    
            httpUrlConn.setUseCaches(false);    
            // 设置请求方式(GET/POST)    
            httpUrlConn.setRequestMethod(requestMethod);    

            if ("GET".equalsIgnoreCase(requestMethod))  {  

             httpUrlConn.connect();    
            }  

            // 当有数据需要提交时    
            if (null != outputStr) {    
                OutputStream outputStream = httpUrlConn.getOutputStream();    
                // 注意编码格式,防止中文乱码    
                outputStream.write(outputStr.getBytes("UTF-8"));    
                outputStream.close();    
            }    

            // 将返回的输入流转换成字符串    
            InputStream inputStream = httpUrlConn.getInputStream();    
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");    
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);    

            String str = null;    
            while ((str = bufferedReader.readLine()) != null) {    
                buffer.append(str);    
            }    
            bufferedReader.close();    
            inputStreamReader.close();    
            // 释放资源    
            inputStream.close();    
            inputStream = null;    
            httpUrlConn.disconnect();    
            jsonObject = JSONObject.parseObject(buffer.toString());    
        } catch (ConnectException ce) {    
         ce.printStackTrace();  
           // log.error("Weixin server connection timed out.");    
        } catch (Exception e) {    
            //log.error("https request error:{}", e);   
         e.printStackTrace();  
        }    
        return jsonObject;    
    }  
    public static void main(String[] args) {
        System.err.println(httpRequest("https://moni.byxgj.com:23134", "GET", null));
        ///createaccount?requestid=1&sa=sa07&sapass=c33&account=0&password=123456&name=张三&group=交易组1&mainaccount=21
    }
}  
 javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching moni.byxgj.com found
    at sun.security.ssl.Alerts.getSSLException(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
    at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
    at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
    at sun.security.ssl.Handshaker.processLoop(Unknown Source)
    at sun.security.ssl.Handshaker.process_record(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)
    at com.wlq.test.MyX509TrustManager.httpRequest(MyX509TrustManager.java:57)
    at com.wlq.test.MyX509TrustManager.main(MyX509TrustManager.java:94)

请问这个错怎么整?网上的方法全部测试过来了

 httpClient方法 报
 javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

ps:如果有直接可用demo,求分享

2个回答

yaodwwy
yaodwwy   2017.09.05 12:43
wlq199101
wlq199101 报了一样的错,不过还是很感谢
2 个月之前 回复
qq_23292875
qq_23292875   2017.09.05 13:50
package my;

import java.io.BufferedReader;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;
import java.io.InputStreamReader;

import java.io.OutputStream;
import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLDecoder;
import java.security.GeneralSecurityException;

import java.security.KeyStore;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.KeyManagerFactory;

import javax.net.ssl.SSLContext;

import javax.net.ssl.TrustManagerFactory;

public class HttpsPost {

private static HttpsURLConnection urlCon = null;
/**
* 获得KeyStore.
* @param keyStorePath
* 密钥库路径
* @param password
* 密码
* @return 密钥库
* @throws Exception
*/

public static KeyStore getKeyStore(String password, String keyStorePath)

throws Exception {

// 实例化密钥库

KeyStore ks = KeyStore.getInstance("JKS");

// 获得密钥库文件流

FileInputStream is = new FileInputStream(keyStorePath);

// 加载密钥库

ks.load(is, password.toCharArray());

// 关闭密钥库文件流

is.close();

return ks;

}

/** 
 * 获得SSLSocketFactory. 
 * @param password 
 *            密码 
 * @param keyStorePath 
 *            密钥库路径 
 * @param trustStorePath 
 *            信任库路径 
 * @return SSLSocketFactory 
 * @throws Exception 
 */  
public static SSLContext getSSLContext(String password,  
        String keyStorePath, String trustStorePath) throws Exception {  
    // 实例化密钥库  
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());  
    // 获得密钥库  
    KeyStore keyStore = getKeyStore(password, keyStorePath);  
    // 初始化密钥工厂  
    keyManagerFactory.init(keyStore, password.toCharArray());  

    // 实例化信任库  
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());  
    // 获得信任库  
    KeyStore trustStore = getKeyStore(password, trustStorePath);  
    // 初始化信任库  
    trustManagerFactory.init(trustStore);  
    // 实例化SSL上下文  
    SSLContext ctx = SSLContext.getInstance("TLS");  
    // 初始化SSL上下文  
    ctx.init(keyManagerFactory.getKeyManagers(),  
            trustManagerFactory.getTrustManagers(), null);  
    // 获得SSLSocketFactory  
    return ctx;  
}  

/** 
 * 初始化HttpsURLConnection. 
 * @param password 
 *            密码 
 * @param keyStorePath 
 *            密钥库路径 
 * @param trustStorePath 
 *            信任库路径 
 * @throws Exception 
 */  
public static void initHttpsURLConnection(String password,  
        String keyStorePath, String trustStorePath) throws Exception {  
    // 声明SSL上下文  
    SSLContext sslContext = null;  
    // 实例化主机名验证接口  
    HostnameVerifier hnv = new MyHostnameVerifier();  
    try {  
        sslContext = getSSLContext(password, keyStorePath, trustStorePath);  
    } catch (GeneralSecurityException e) {  
        e.printStackTrace();  
    }  
    if (sslContext != null) {  
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext  
                .getSocketFactory());  
    }  
    HttpsURLConnection.setDefaultHostnameVerifier(hnv);  
}  

/** 
 * 发送请求. 
 * @param httpsUrl 
 *            请求的地址 
 * @param xmlStr 
 *            请求的数据 
 */  
public static String postLogin(String httpsUrl,Map<String, Object> map) {  
    String sessionId = "";  
    String cookieVal = "";  
    String key = null; 
    OutputStream out = null;
    try {  
        urlCon = (HttpsURLConnection) (new URL(httpsUrl)).openConnection();  
        urlCon.setDoInput(true);  
        urlCon.setDoOutput(true);  
        urlCon.setReadTimeout(500000);
        urlCon.setConnectTimeout(500000);
        urlCon.setRequestProperty("Connection", "Keep-Alive");  
        urlCon.setRequestMethod("POST");  
        urlCon.setUseCaches(false);  
        // POST请求 
        String params = "";
        out = urlCon.getOutputStream();
        if (map != null && map.size() >= 1) {
            Iterator<Entry<String, Object>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = (Entry<String, Object>) it.next();
                params += entry.getKey() + "=" + entry.getValue() + "&";
            }
        }
        out.write(params.getBytes());
        out.flush();
        out.close();

        for(int i = 1; (key = urlCon.getHeaderFieldKey(i)) != null; i++){  
            if(key.equalsIgnoreCase("set-cookie")){  
                cookieVal = urlCon.getHeaderField(i);  
                cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));  
                sessionId = sessionId + cookieVal + ";";  
            }  
        }  
        // 读取响应 
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
        String lines;
        StringBuffer sb = new StringBuffer("");
        while ((lines = reader.readLine()) != null) {
            lines = URLDecoder.decode(lines, "utf-8");
            sb.append(lines);
        }
        System.out.println(sb);
        reader.close();
        // 断开连接 
        urlCon.disconnect(); 
    } catch (MalformedURLException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    } catch (Exception e) {  
        e.printStackTrace();  
    }
    return sessionId;
}  

/**
 * 验证证书并登录
 * @throws Exception 
 * 
 */
public static String initAndLogin(String httpsUrl, Map<String, Object> map)
        throws Exception {
    String keyStorePWD ="password";
    String string = HttpsPost.class.getResource("/").toString();
    String replace = string.replace("file:/", "");
    String keyStorePath ="密钥库路径";
    String trustStorePath ="信任库路径";
    //证书验证
    HttpsPost.initHttpsURLConnection(keyStorePWD, keyStorePath, trustStorePath);
    //发送登录请求
    return  postLogin(httpsUrl, map);
}


    /**
     * 通过拼接的方式构造请求内容,实现参数传输以及文件传输
     * @param actionUrl 访问的服务器URL
     * @param params 普通参数
     * @param files 文件参数
     * @return
     * @throws IOException
     */
    public static String post(String actionUrl, Map<String, String> params, Map<String, File> files,String cookieVal) throws IOException{

        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";
        URL url = new URL(actionUrl);
        urlCon = (HttpsURLConnection) url.openConnection();  

        urlCon.setReadTimeout(5 * 1000); // 缓存的最长时间
        urlCon.setDoInput(true);// 允许输入
        urlCon.setDoOutput(true);// 允许输出
        urlCon.setUseCaches(false); // 不允许使用缓存
        urlCon.setRequestMethod("POST");
        urlCon.setRequestProperty("Cookie",cookieVal);  
        urlCon.setRequestProperty("connection", "keep-alive");
        urlCon.setRequestProperty("Charsert", "UTF-8");
        urlCon.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

        // 首先组拼文本类型的参数
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet())
        {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
            sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }
            System.out.println(sb.toString());
        DataOutputStream outStream = new DataOutputStream(urlCon.getOutputStream());
        outStream.write(sb.toString().getBytes());
        InputStream in = null;
        // 发送文件数据
        if (files != null)
        {
            for (Map.Entry<String, File> file : files.entrySet())
            {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\""  + file.getValue().getName() + "\"" + LINEND);
                sb1.append(LINEND);
                System.out.println(sb1);
                outStream.write(sb1.toString().getBytes());

                InputStream is = new FileInputStream(file.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1)
                {
                    outStream.write(buffer, 0, len);
                }

                is.close();
                outStream.write(LINEND.getBytes());
            }
            // 请求结束标志
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
            outStream.write(end_data);
            outStream.flush();
            outStream.close();
            urlCon.disconnect();

            // 读取返回数据    
            BufferedReader reader = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
            String lines;
            StringBuffer ssb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = URLDecoder.decode(lines, "utf-8");
                ssb.append(lines);
            }
            System.out.println(ssb.toString());
            reader.close();
            // 断开连接 
            urlCon.disconnect(); 

            return ssb.toString();
        }
        return null;
    }

    /**
     * 退出
     */
    public static String postLogout(String cookieVal,String httpsUrl) {
        StringBuffer sb = new StringBuffer("");
        OutputStream out = null;
        try {
            urlCon = (HttpsURLConnection) (new URL(httpsUrl)).openConnection();
            urlCon.setDoInput(true);
            urlCon.setDoOutput(true);
            urlCon.setReadTimeout(500000);
            urlCon.setConnectTimeout(500000);
            urlCon.setRequestMethod("POST");
            urlCon.setRequestProperty("Cookie",cookieVal);  
            urlCon.setUseCaches(false);
            // POST请求
            String params = "";
            out = urlCon.getOutputStream();
            out.write(params.getBytes());
            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
            String lines;

            while ((lines = reader.readLine()) != null) {
                lines = URLDecoder.decode(lines, "utf-8");
                sb.append(lines);
            }
            System.out.println(sb);
            reader.close();
            // 断开连接
             urlCon.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    /** 
     * 测试方法. 
     * @param args 
     * @throws Exception 
     */  
    public static void main(String[] args) throws Exception {  
        // 密码  
        String password = "xxxxx";  
        // 密钥库  
        String keyStorePath = "D:\\xxxx.xxxxx";  
        // 信任库  
        String trustStorePath = "D:\\xxxx.xxxx";  
        // 本地起的https服务  
        String httpsUrl = "https://xxxxx:xxx/xxxx/xxxxx";  
        // 传输文本  
    }  

}


package my;

import javax.net.ssl.HostnameVerifier;

import javax.net.ssl.SSLSession;

/**

  • 实现用于主机名验证的基接口。
  • 在握手期间,如果 URL 的主机名和服务器的标识主机名不匹配,则验证机制可以回调此接口的实现程序来确定是否应该允许此连接。 */
    public class MyHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String hostname, SSLSession session) {
    return true;
    }
    }
Csdn user default icon
上传中...
上传图片
插入图片