精华内容
下载资源
问答
  • Java请求https接口

    千次阅读 2020-06-13 14:44:09
    import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io....
    package test;
    
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLSession;
    
    /**
     * HTTP请求
     */
    public class HTTPUtils {
        private static final int TIMEOUT = 45000;
        public static final String ENCODING = "UTF-8";
    
        /**
         * 创建请求连接
         * url:地址
         * method:方法
         * headerParameters:请求头
         * body:请求内容
         */
        private static HttpURLConnection createConnection(String url,
                String method, Map<String, String> headerParameters, String body)
                throws Exception {
            URL Url = new URL(url);
            trustAllHttpsCertificates();
            HttpURLConnection httpConnection = (HttpURLConnection) Url
                    .openConnection();
            // 设置请求时间
            httpConnection.setConnectTimeout(TIMEOUT);
            // 设置 header
            if (headerParameters != null) {
                Iterator<String> iteratorHeader = headerParameters.keySet()
                        .iterator();
                while (iteratorHeader.hasNext()) {
                    String key = iteratorHeader.next();
                    httpConnection.setRequestProperty(key,
                            headerParameters.get(key));
                }
            }
            httpConnection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=" + ENCODING);
            // 设置请求方法
            httpConnection.setRequestMethod(method);
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
            // 写query数据流
            if (!(body == null || body.trim().equals(""))) {
                OutputStream writer = httpConnection.getOutputStream();
                try {
                    writer.write(body.getBytes(ENCODING));
                } finally {
                    if (writer != null) {
                        writer.flush();
                        writer.close();
                    }
                }
            }
    
            // 请求结果
            int responseCode = httpConnection.getResponseCode();
            if (responseCode != 200) {
                throw new Exception(responseCode
                        + ":"
                        + inputStream2String(httpConnection.getErrorStream(),
                                ENCODING));
            }
            return httpConnection;
        }
    
        /**
         * POST请求
         * address:请求地址
         * headerParameters:请求头
         * body:请求内容
         */
        public static String post(String address,
                Map<String, String> headerParameters, String body) throws Exception {
    
            return proxyHttpRequest(address, "POST", null,
                    getRequestBody(headerParameters));
        }
    
        /**
         * GET请求
         * address:请求地址
         * headerParameters:请求头
         * body:请求内容
         */
        public static String get(String address,
                Map<String, String> headerParameters, String body) throws Exception {
    
            return proxyHttpRequest(address + "?"
                    + getRequestBody(headerParameters), "GET", null, null);
        }
    
        /**
         * 读取网络文件
         * address:地址
         * headerParameters:请求头
         * file:文件
         */
        public static String getFile(String address,
                Map<String, String> headerParameters, File file) throws Exception {
            String result = "fail";
            HttpURLConnection httpConnection = null;
            try {
                httpConnection = createConnection(address, "POST", null,
                        getRequestBody(headerParameters));
                result = readInputStream(httpConnection.getInputStream(), file);
            } catch (Exception e) {
                throw e;
            } finally {
                if (httpConnection != null) {
                    httpConnection.disconnect();
                }
            }
            return result;
        }
        
        public static byte[] getFileByte(String address,
                Map<String, String> headerParameters) throws Exception {
            byte[] result = null;
            HttpURLConnection httpConnection = null;
            try {
                httpConnection = createConnection(address, "POST", null,
                        getRequestBody(headerParameters));
                result = readInputStreamToByte(httpConnection.getInputStream());
            } catch (Exception e) {
                throw e;
            } finally {
                if (httpConnection != null) {
                    httpConnection.disconnect();
                }
            }
            return result;
        }
    
        public static String readInputStream(InputStream in, File file)
                throws Exception {
            FileOutputStream out = null;
            ByteArrayOutputStream output = null;
            try {
                output = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) != -1) {
                    output.write(buffer, 0, len);
                }
                out = new FileOutputStream(file);
                out.write(output.toByteArray());
            } catch (Exception e) {
                throw e;
            } finally {
                if (output != null) {
                    output.close();
                }
                if (out != null) {
                    out.close();
                }
            }
            return "success";
        }
        
        public static byte[] readInputStreamToByte(InputStream in) throws Exception {
            FileOutputStream out = null;
            ByteArrayOutputStream output = null;
            byte[] byteFile = null;
            try {
                output = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) != -1) {
                    output.write(buffer, 0, len);
                }
                byteFile = output.toByteArray();
            } catch (Exception e) {
                throw e;
            } finally {
                if (output != null) {
                    output.close();
                }
                if (out != null) {
                    out.close();
                }
            }
    
            return byteFile;
        }
    
        public static String proxyHttpRequest(String address, String method,
                Map<String, String> headerParameters, String body) throws Exception {
            String result = null;
            HttpURLConnection httpConnection = null;
            try {
                httpConnection = createConnection(address, method, headerParameters, body);
                String encoding = "UTF-8";
                if (httpConnection.getContentType() != null
                        && httpConnection.getContentType().indexOf("charset=") >= 0) {
                    encoding = httpConnection.getContentType().substring(httpConnection.getContentType().indexOf("charset=") + 8);
                }
                result = inputStream2String(httpConnection.getInputStream(), encoding);
            } catch (Exception e) {
                throw e;
            } finally {
                if (httpConnection != null) {
                    httpConnection.disconnect();
                }
            }
            return result;
        }
    
        /**
         * 将参数化为 body
         * @param params
         * @return
         */
        public static String getRequestBody(Map<String, String> params) {
            return getRequestBody(params, true);
        }
    
        /**
         * 将参数化为 body
         * @param params
         * @return
         */
        public static String getRequestBody(Map<String, String> params,
                boolean urlEncode) {
            StringBuilder body = new StringBuilder();
            Iterator<String> iteratorHeader = params.keySet().iterator();
            while (iteratorHeader.hasNext()) {
                String key = iteratorHeader.next();
                String value = params.get(key);
                if (urlEncode) {
                    try {
                        body.append(key + "=" + URLEncoder.encode(value, ENCODING)
                                + "&");
                    } catch (UnsupportedEncodingException e) {
                    	
                    }
                } else {
                    body.append(key + "=" + value + "&");
                }
            }
            if (body.length() == 0) {
                return "";
            }
            return body.substring(0, body.length() - 1);
        }
    
        private static String inputStream2String(InputStream input, String encoding)
                throws IOException {
            BufferedReader reader = new BufferedReader(new InputStreamReader(input,
                    encoding));
            StringBuilder result = new StringBuilder();
            String temp = null;
            while ((temp = reader.readLine()) != null) {
                result.append(temp);
            }
    
            return result.toString();
    
        }
    
        private static void trustAllHttpsCertificates() throws Exception {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String str, SSLSession session) {
                    return true;
                }
            });
            javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
            javax.net.ssl.TrustManager tm = new miTM();
            trustAllCerts[0] = tm;
            javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
                    .getInstance("SSL");
            sc.init(null, trustAllCerts, null);
            javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
                    .getSocketFactory());
        }
    
    
        //设置 https 请求证书
        static class miTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            
            public boolean isServerTrusted(
                    java.security.cert.X509Certificate[] certs) {
                return true;
            }
            
            public boolean isClientTrusted(
                    java.security.cert.X509Certificate[] certs) {
                return true;
            }
            
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType)
                    throws java.security.cert.CertificateException {
                return;
            }
            
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType)
                    throws java.security.cert.CertificateException {
                return;
            }
        }
    
        public static void main(String[] args) {
        	try {
                //请求地址
                String address = "https://api.bknks.com/getUser";
                //请求参数
                Map<String, String> params = new HashMap<String, String>();
                params.put("tel", "13299999999");
                // 调用 post 请求
                String res = get(address, params, null);
                System.out.println(res.replaceAll("[\\(\\)]", ""));//打印返回参数
            } catch (Exception e) {
                // TODO 异常
                e.printStackTrace();
            }
        }
    
    }
    
    展开全文
  • nginx下配好https证书,java 请求https接口会reset。tomcat下配好证书,就没有问题。
  • Java 请求https接口不需要安装证书

    千次阅读 2017-05-25 16:50:17
    Java 请求https接口不需要安装证书,获取到信任的cilent


    /**
    * SSL请求HTTPS 不需要证书,用获取到的Client发起请求即可

             * org.apache.http.impl.client.CloseableHttpClient
    */
    public static CloseableHttpClient createSSLClientDefault(){
    try {
                 SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    //信任所有
                    @Override
    public boolean isTrusted(java.security.cert.X509Certificate[] chain, String authType)
    throws java.security.cert.CertificateException {
    return true;
    }
                 }).build();
                 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                 return HttpClients.custom().setSSLSocketFactory(sslsf).build();
             } catch (KeyManagementException e) {
            LOGGER.error("createSSLClientDefault KeyManagementException error",e);
             } catch (NoSuchAlgorithmException e) {
            LOGGER.error("createSSLClientDefault NoSuchAlgorithmException error",e);
             } catch (KeyStoreException e) {
            LOGGER.error("createSSLClientDefault KeyStoreException error",e);
             }
             return  HttpClients.createDefault();
    }

    展开全文
  • java ssl 证书验证有两种方式:1是将证书导入到java安全证...第1种方式导入证书后,请求https时就直接报错:javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternati...

    java ssl 证书验证有两种方式:1是将证书导入到java安全证书库中;2是将证书通过keytool导出一个密钥文件,然后通过代码加载该文件进行验证。

    第1种方式导入证书后,请求https时就直接报错:

    javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present

    不知道怎样解决。

    第2种方式,导入文件命令:

    D:\>keytool -importcert -alias test -file test.cer -keystore test.keystore

    java代码加载test.keystore文件验证:

    package test;

    import java.io.BufferedReader;

    import java.io.FileInputStream;

    import java.io.IOException;

    import java.io.InputStream;

    import java.io.InputStreamReader;

    import java.io.OutputStream;

    import java.io.StringWriter;

    import java.net.HttpURLConnection;

    import java.net.URL;

    import java.security.KeyStore;

    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.TrustManagerFactory;

    import org.apache.commons.lang.StringUtils;

    import org.apache.log4j.Logger;

    public class HttpsCommonUtil {

    private static Logger logger = Logger.getLogger(HttpsCommonUtil.class);

    static HostnameVerifier hv = new HostnameVerifier() {

    public boolean verify(String urlHostName, SSLSession session) {

    return true;

    }

    };

    public static String doGet(String url, String params, Map headers) throws Exception {

    HttpsURLConnection conn = null;

    OutputStream out = null;

    String rsp = null;

    try {

    try {

    trustAllHttpsCertificates();

    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    String urlStr = url;

    if(StringUtils.isNotEmpty(params))

    urlStr += "?" + params;

    conn = getConnection(new URL(urlStr), "GET", headers);

    //conn.setConnectTimeout(connectTimeout);

    //conn.setReadTimeout(readTimeout);

    } catch (Exception e) {

    logger.error("GET_CONNECTOIN_ERROR, URL = " + url, e);

    throw e;

    }

    try {

    out = conn.getOutputStream();

    rsp = getResponseAsString(conn);

    } catch (IOException e) {

    logger.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);

    throw e;

    }

    } finally {

    if (out != null) {

    out.close();

    }

    if (conn != null) {

    conn.disconnect();

    }

    }

    return rsp;

    }

    public static String doPost(String url, String params, Map headers) throws Exception {

    HttpsURLConnection conn = null;

    OutputStream out = null;

    String rsp = null;

    try {

    try {

    trustAllHttpsCertificates();

    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    conn = getConnection(new URL(url), "POST", headers);

    //conn.setConnectTimeout(connectTimeout);

    //conn.setReadTimeout(readTimeout);

    } catch (Exception e) {

    logger.error("GET_CONNECTOIN_ERROR, URL = " + url, e);

    throw e;

    }

    try {

    out = conn.getOutputStream();

    byte[] content = {};

    if (StringUtils.isNotEmpty(params)) {

    content = params.getBytes("utf-8");

    }

    out.write(content);

    rsp = getResponseAsString(conn);

    } catch (IOException e) {

    logger.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);

    throw e;

    }

    } finally {

    if (out != null) {

    out.close();

    }

    if (conn != null) {

    conn.disconnect();

    }

    }

    return rsp;

    }

    private static HttpsURLConnection getConnection(URL url, String method,

    Map headers) throws IOException {

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    conn.setRequestMethod(method);

    conn.setDoInput(true);

    conn.setDoOutput(true);

    conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");

    conn.setRequestProperty("User-Agent", "stargate");

    //conn.setRequestProperty("Content-Type", ctype);

    for(Entry entry:headers.entrySet()) {

    conn.setRequestProperty(entry.getKey(), entry.getValue());

    }

    return conn;

    }

    private static String getResponseAsString(HttpURLConnection conn)

    throws IOException {

    String charset = getResponseCharset(conn.getContentType());

    InputStream es = conn.getErrorStream();

    if (es == null) {

    return getStreamAsString(conn.getInputStream(), charset);

    } else {

    String msg = getStreamAsString(es, charset);

    if (StringUtils.isEmpty(msg)) {

    throw new IOException(conn.getResponseCode() + ":"

    + conn.getResponseMessage());

    } else {

    throw new IOException(msg);

    }

    }

    }

    private static String getStreamAsString(InputStream stream, String charset)

    throws IOException {

    try {

    BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));

    StringWriter writer = new StringWriter();

    char[] chars = new char[256];

    int count = 0;

    while ((count = reader.read(chars)) > 0) {

    writer.write(chars, 0, count);

    }

    return writer.toString();

    } finally {

    if (stream != null) {

    stream.close();

    }

    }

    }

    private static String getResponseCharset(String ctype) {

    String charset = "utf-8";

    if (!StringUtils.isEmpty(ctype)) {

    String[] params = ctype.split(";");

    for (String param : params) {

    param = param.trim();

    if (param.startsWith("charset")) {

    String[] pair = param.split("=", 2);

    if (pair.length == 2) {

    if (!StringUtils.isEmpty(pair[1])) {

    charset = pair[1].trim();

    }

    }

    break;

    }

    }

    }

    return charset;

    }

    private static void trustAllHttpsCertificates() throws Exception {

    String key=PropertiesUtil.get("properties/keystore", "orderReceipt.key.path");

    String pass=PropertiesUtil.get("properties/keystore", "orderReceipt.key.pass");

    KeyStore keystore=KeyStore.getInstance("JKS"); //创建一个keystore来管理密钥库

    keystore.load(new FileInputStream(key),pass.toCharArray());

    //创建jkd密钥访问库

    TrustManagerFactory tmf=TrustManagerFactory.getInstance("SunX509");

    tmf.init(keystore); //验证数据,可以不传入key密码

    //创建TrustManagerFactory,管理授权证书

    SSLContext sslc=SSLContext.getInstance("SSLv3");

    // 构造SSL环境,指定SSL版本为3.0,也可以使用TLSv1,但是SSLv3更加常用。

    sslc.init(null,tmf.getTrustManagers(),null);

    //KeyManager[] 第一个参数是授权的密钥管理器,用来授权验证。第二个是被授权的证书管理器,

    //用来验证服务器端的证书。只验证服务器数据,第一个管理器可以为null

    //构造ssl环境

    HttpsURLConnection.setDefaultSSLSocketFactory(sslc.getSocketFactory());

    }

    public static void main(String[] args) {

    }

    }

    orderReceipt.key.path是test.keystore存放路径,orderReceipt.key.pass是你导出该文件时设置的密码。

    在网上找的资料说不需要执行HttpsURLConnection.setDefaultHostnameVerifier(hv);这行代码,但我去掉这行代码后,就会报错:

    javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present

    而在网上找的都是说直接绕过证书验证这种方式,但这种方式放到线上后,一开始能接通,但过了几天后就报错:

    sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    大家是怎样对接https接口的,有经验的朋友讨论下0..0

    展开全文
  • java ssl 证书验证有两种方式:1是将证书导入到java安全证...第1种方式导入证书后,请求https时就直接报错:javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternati...

    java ssl 证书验证有两种方式:1是将证书导入到java安全证书库中;2是将证书通过keytool导出一个密钥文件,然后通过代码加载该文件进行验证。

    第1种方式导入证书后,请求https时就直接报错:

    javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present

    不知道怎样解决。

    第2种方式,导入文件命令:

    D:\>keytool -importcert -alias test -file test.cer -keystore test.keystore

    java代码加载test.keystore文件验证:

    package test;

    import java.io.BufferedReader;

    import java.io.FileInputStream;

    import java.io.IOException;

    import java.io.InputStream;

    import java.io.InputStreamReader;

    import java.io.OutputStream;

    import java.io.StringWriter;

    import java.net.HttpURLConnection;

    import java.net.URL;

    import java.security.KeyStore;

    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.TrustManagerFactory;

    import org.apache.commons.lang.StringUtils;

    import org.apache.log4j.Logger;

    public class HttpsCommonUtil {

    private static Logger logger = Logger.getLogger(HttpsCommonUtil.class);

    static HostnameVerifier hv = new HostnameVerifier() {

    public boolean verify(String urlHostName, SSLSession session) {

    return true;

    }

    };

    public static String doGet(String url, String params, Map headers) throws Exception {

    HttpsURLConnection conn = null;

    OutputStream out = null;

    String rsp = null;

    try {

    try {

    trustAllHttpsCertificates();

    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    String urlStr = url;

    if(StringUtils.isNotEmpty(params))

    urlStr += "?" + params;

    conn = getConnection(new URL(urlStr), "GET", headers);

    //conn.setConnectTimeout(connectTimeout);

    //conn.setReadTimeout(readTimeout);

    } catch (Exception e) {

    logger.error("GET_CONNECTOIN_ERROR, URL = " + url, e);

    throw e;

    }

    try {

    out = conn.getOutputStream();

    rsp = getResponseAsString(conn);

    } catch (IOException e) {

    logger.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);

    throw e;

    }

    } finally {

    if (out != null) {

    out.close();

    }

    if (conn != null) {

    conn.disconnect();

    }

    }

    return rsp;

    }

    public static String doPost(String url, String params, Map headers) throws Exception {

    HttpsURLConnection conn = null;

    OutputStream out = null;

    String rsp = null;

    try {

    try {

    trustAllHttpsCertificates();

    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    conn = getConnection(new URL(url), "POST", headers);

    //conn.setConnectTimeout(connectTimeout);

    //conn.setReadTimeout(readTimeout);

    } catch (Exception e) {

    logger.error("GET_CONNECTOIN_ERROR, URL = " + url, e);

    throw e;

    }

    try {

    out = conn.getOutputStream();

    byte[] content = {};

    if (StringUtils.isNotEmpty(params)) {

    content = params.getBytes("utf-8");

    }

    out.write(content);

    rsp = getResponseAsString(conn);

    } catch (IOException e) {

    logger.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);

    throw e;

    }

    } finally {

    if (out != null) {

    out.close();

    }

    if (conn != null) {

    conn.disconnect();

    }

    }

    return rsp;

    }

    private static HttpsURLConnection getConnection(URL url, String method,

    Map headers) throws IOException {

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    conn.setRequestMethod(method);

    conn.setDoInput(true);

    conn.setDoOutput(true);

    conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html");

    conn.setRequestProperty("User-Agent", "stargate");

    //conn.setRequestProperty("Content-Type", ctype);

    for(Entry entry:headers.entrySet()) {

    conn.setRequestProperty(entry.getKey(), entry.getValue());

    }

    return conn;

    }

    private static String getResponseAsString(HttpURLConnection conn)

    throws IOException {

    String charset = getResponseCharset(conn.getContentType());

    InputStream es = conn.getErrorStream();

    if (es == null) {

    return getStreamAsString(conn.getInputStream(), charset);

    } else {

    String msg = getStreamAsString(es, charset);

    if (StringUtils.isEmpty(msg)) {

    throw new IOException(conn.getResponseCode() + ":"

    + conn.getResponseMessage());

    } else {

    throw new IOException(msg);

    }

    }

    }

    private static String getStreamAsString(InputStream stream, String charset)

    throws IOException {

    try {

    BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));

    StringWriter writer = new StringWriter();

    char[] chars = new char[256];

    int count = 0;

    while ((count = reader.read(chars)) > 0) {

    writer.write(chars, 0, count);

    }

    return writer.toString();

    } finally {

    if (stream != null) {

    stream.close();

    }

    }

    }

    private static String getResponseCharset(String ctype) {

    String charset = "utf-8";

    if (!StringUtils.isEmpty(ctype)) {

    String[] params = ctype.split(";");

    for (String param : params) {

    param = param.trim();

    if (param.startsWith("charset")) {

    String[] pair = param.split("=", 2);

    if (pair.length == 2) {

    if (!StringUtils.isEmpty(pair[1])) {

    charset = pair[1].trim();

    }

    }

    break;

    }

    }

    }

    return charset;

    }

    private static void trustAllHttpsCertificates() throws Exception {

    String key=PropertiesUtil.get("properties/keystore", "orderReceipt.key.path");

    String pass=PropertiesUtil.get("properties/keystore", "orderReceipt.key.pass");

    KeyStore keystore=KeyStore.getInstance("JKS"); //创建一个keystore来管理密钥库

    keystore.load(new FileInputStream(key),pass.toCharArray());

    //创建jkd密钥访问库

    TrustManagerFactory tmf=TrustManagerFactory.getInstance("SunX509");

    tmf.init(keystore); //验证数据,可以不传入key密码

    //创建TrustManagerFactory,管理授权证书

    SSLContext sslc=SSLContext.getInstance("SSLv3");

    // 构造SSL环境,指定SSL版本为3.0,也可以使用TLSv1,但是SSLv3更加常用。

    sslc.init(null,tmf.getTrustManagers(),null);

    //KeyManager[] 第一个参数是授权的密钥管理器,用来授权验证。第二个是被授权的证书管理器,

    //用来验证服务器端的证书。只验证服务器数据,第一个管理器可以为null

    //构造ssl环境

    HttpsURLConnection.setDefaultSSLSocketFactory(sslc.getSocketFactory());

    }

    public static void main(String[] args) {

    }

    }

    orderReceipt.key.path是test.keystore存放路径,orderReceipt.key.pass是你导出该文件时设置的密码。

    在网上找的资料说不需要执行HttpsURLConnection.setDefaultHostnameVerifier(hv);这行代码,但我去掉这行代码后,就会报错:

    javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present

    而在网上找的都是说直接绕过证书验证这种方式,但这种方式放到线上后,一开始能接通,但过了几天后就报错:

    sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    大家是怎样对接https接口的,有经验的朋友讨论下0..0

    展开全文
  • java 请求https接口 证书验证

    千次阅读 2016-07-25 15:04:52
    java ssl 证书验证有两种方式:1是将证书导入到java安全证书库...第1种方式导入证书后,请求https时就直接报错: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alte...
  • 解决JAVA请求HTTPS接口需要验证问题

    千次阅读 2018-01-30 23:25:46
    最近做项目,由于安全性问题,由原来的http接口改为了https接口,那么原来写的java调用http接口的工具类就不能够使用了,上网查找资料,折腾了半天,终于搞定了,详细代码如下: package com.cnmts.util; import...
  • 创建多线程时,如果使用同一个runnable对象,则多个线程共享一个runnable资源 public class ...@Overridepublic void run() {while(true){try {Thread.sleep((long)Math./**********************https 接口'****...
  • import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java....
  • java 请求微信https接口

    2020-05-13 16:10:51
    但是请求https协议是需要ssl证书的,在网上看了很多方法 看到了一个跳过ssl校验的方法 如下: 小程序端: wx.getUserInfo({ success: function(res) { var iv = res.iv;//这是微信加密算法的初始向量 var ...
  • java 请求https get 接口证书验证问题

    千次阅读 2018-12-19 14:55:37
    1,通过重新定义X509TrustManager证书管理器可以解决相关问题。 @Test public void testToken() throws KeyManagementException, ... //采用绕过验证的方式处理https请求 SSLContext ssl...
  • 1,创建java类继承 X509TrustManager,绕过证书用 import javax.net.ssl.X509TrustManager; public class MyX509TrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[]...
  • /**********************https 接口'*******************//*** 安全证书管理器*/public class MyX509TrustManager implements X509TrustManager {@Overridepublic void checkClientTrusted(final X509Certificate[] ...
  • packagecom.inspur.demo....importjava.io.File;importjava.io.IOException;importjava.nio.CharBuffer;importjava.util.ArrayList;importjava.util.List;importjava.util.concurrent.CountDownLatch;impor...
  • /**********************https 接口'*******************/ /*** 安全证书管理器*/public class MyX509TrustManager implements X509TrustManager { @Override public void checkClientTrusted(final X509Certif...
  • java请求https

    2015-08-18 19:21:32
    // 这是微信的请求发红包的接口,需要下载秘钥文件的 [code="java"]package com.wx.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java....
  • 问题现象:和客户对接时,客户请求我们的 https 接口报错 java.net.SocketException:Connection reset。原因分析:根据客户提供的服务异常信息,可以大略猜到是 SSL 的问题。我们这边的 Nginx SSL 配置为 :ssl_...
  • 首先是三个返回的实体类BaseVo.javapackage https2;import java.io.Serializable;import java.lang.reflect.InvocationTargetException;import java.util.ArrayList;import java.util.List;public class BaseVo ...
  • 项目需要访问https请求但是一直报错No subject alternative names matching IP address XXX found.随查找各种API,原来https是双向握手,必须指定主机HttpsURLConnection conn = (HttpsURLConnection) url.open...
  • 主要原因为接口服务器配置的https证书不合法,导致服务端返回的数字证书没有通过客户端的校验。 二、解决方法 1.使用合法的https证书; 2.接口调用跳过证书校验(大部分使用该方法); 代码如下: ...
  • 关于在Java中调用REST接口,首先来说一下JAX-RS。JAX-RS是JAVA EE6 引入的一个新技术。JAX-RS即Java API for RESTful Web Services,是一个Java 编程语言的应用程序接口,支持按照表述性状态转移(REST)架构风格创建...
  • * 证书信任管理器(用于https请求) * @date 2013-08-08 */ public class MyX509TrustManager implements X509TrustManager{ public void checkClientTrusted(X509Certificate[] arg0, String arg1) ...
  • 此文章记录使用httppost 方式请求https接口,安全证书默认全部接收。 此方法经测试为可行,希望可以帮到需要的朋友。 /** * 请求https的接口 *  * @param url 接口地址 * @param requestSoap 请求报文 * @param ...
  • 首先是三个返回的实体类 ...package https2; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; public class B...
  • 第一步:首先获取HTTPS网站的证书-----...第二步:将步骤一的*.cer文件拷贝到'%JAVA_HOME%\jre\lib\security\cacerts'路径下第三步:配置环境变量vi /etc/profilei插入添加以下三句export到文件最后 注意JAVA_HOME的...
  • JAVA WEB】使用HTTPS请求外部接口

    千次阅读 2017-02-25 15:36:02
    如何使用HTTPS请求外部接口
  • 文章目录HTTP请求证书验证HTTPS通讯出错处理 HTTP是基于TCP/IP的应用层协议,简单、便捷。RESTFUL是一种基于HTTP的网络应用程序设计风格和开发方式,方便实现跨平台的业务接口。 HTTP请求 Java中通过...
  • import java.io.*; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert....
  • import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.SecureRandom; import java.security.cert.Ce.....
  • Java 调用Http和Https接口

    千次阅读 2019-08-09 16:44:21
    Java调用Http接口和Https接口 大多数我们调用的接口都是Http的,很少有Https的接口,近期做了个项目就用到和Https接口请求调用,和大家分享一下心得。Http接口和Https接口主要是区别还是Https存在一个证书验证。...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,180
精华内容 472
关键字:

java请求https接口

java 订阅