Example usage for javax.net.ssl SSLContext getInstance

List of usage examples for javax.net.ssl SSLContext getInstance

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getInstance.

Prototype

public static SSLContext getInstance(String protocol, Provider provider) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SSLContext object that implements the specified secure socket protocol.

Usage

From source file:com.ct855.util.HttpsClientUtil.java

public static String postUrl(String url, Map<String, String> params)
        throws IOException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    String data = "";
    for (String key : params.keySet()) {
        data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
    }/*from   ww w.ja va  2s  . c om*/
    data = data.substring(1);

    System.out.println("postUrl=>data:" + data);
    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);
    aConnection.setDoInput(true);
    aConnection.setRequestMethod("POST");
    OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(aConnection.getOutputStream());
    streamToAuthorize.write(data);
    streamToAuthorize.flush();
    streamToAuthorize.close();
    InputStream resultStream = aConnection.getInputStream();
    BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
    StringBuffer aResponse = new StringBuffer();
    String aLine = aReader.readLine();
    while (aLine != null) {
        aResponse.append(aLine + "\n");
        aLine = aReader.readLine();
    }
    resultStream.close();
    return aResponse.toString();
}

From source file:com.longtime.ajy.support.weixin.HttpsKit.java

/**
 * ??Get/*from  ww  w.  jav  a  2s . c o m*/
 * 
 * @param url
 * @return
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws KeyManagementException
 */
public static String get(String url) {//throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
    InputStream in = null;
    HttpsURLConnection http = null;

    try {
        StringBuffer bufferRes = null;
        TrustManager[] tm = { new MyX509TrustManager() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory  
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        URL urlGet = new URL(url);
        http = (HttpsURLConnection) urlGet.openConnection();
        // 
        http.setConnectTimeout(TIME_OUT_CONNECT);
        // ? --??
        http.setReadTimeout(TIME_OUT_READ);
        http.setRequestMethod("GET");
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        http.setSSLSocketFactory(ssf);
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();

        in = http.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
        String valueString = null;
        bufferRes = new StringBuffer();
        while ((valueString = read.readLine()) != null) {
            bufferRes.append(valueString);
        }
        return bufferRes.toString();
    } catch (Exception e) {
        logger.error(String.format("HTTP GET url=[%s] due to fail.", url), e);
    } finally {
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP GET url=[%s] close inputstream due to fail.", url), e);
            }
        }
        if (http != null) {
            // 
            http.disconnect();
        }
    }

    return StringUtils.EMPTY;

}

From source file:com.wx.kernel.util.HttpKit.java

private static SSLSocketFactory initSSLSocketFactory() {
    try {/*from  www .  j  a  v a  2  s . com*/
        TrustManager[] tm = { new HttpKit().new TrustAnyTrustManager() };
        SSLContext sslContext = SSLContext.getInstance("TLS", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        return sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ct855.util.HttpsClientUtil.java

public static String testIt(String https_url, Map<String, String> map, String method)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {

    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();

    URL url;//from   w w w.  j ava  2  s .c o m
    try {

        url = new URL(https_url);

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

        con.setRequestMethod(method);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            con.setRequestProperty(entry.getKey(), entry.getValue());
        }

        con.setSSLSocketFactory(ssf);
        //dumpl all cert info
        //print_https_cert(con);
        //dump all the content
        return print_content(con);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.hichengdai.qlqq.front.util.HttpKit.java

/**
 * ?http?//from ww  w  . ja v a2  s  . co  m
 * 
 * @param url
 * @param method
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL _url = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
    // ??
    http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier());
    // 
    http.setConnectTimeout(25000);
    // ? --??
    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    if (null != headers && !headers.isEmpty()) {
        for (Entry<String, String> entry : headers.entrySet()) {
            http.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}

From source file:com.gson.util.HttpKit.java

/**
 * ?http?// ww w .  ja  v  a  2 s.  co m
 * @param url
 * @param method
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
private static HttpsURLConnection initHttps(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    TrustManager[] tm = { new MyX509TrustManager() };
    System.setProperty("https.protocols", "SSLv3");
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory  
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    URL _url = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
    // ??
    http.setHostnameVerifier(new HttpKit().new TrustAnyHostnameVerifier());
    // 
    http.setConnectTimeout(25000);
    // ? --??
    http.setReadTimeout(25000);
    http.setRequestMethod(method);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    http.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
    if (null != headers && !headers.isEmpty()) {
        for (Entry<String, String> entry : headers.entrySet()) {
            http.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    http.setSSLSocketFactory(ssf);
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    return http;
}

From source file:com.longtime.ajy.support.weixin.HttpsKit.java

/**
 * ??Post/*from   w  ww .  j  av  a  2 s .c o  m*/
 * 
 * @param url
 * @param params
 * @return
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static String post(String url, String params) {//throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {

    OutputStream out = null;
    InputStream in = null;
    HttpsURLConnection http = null;
    try {
        StringBuffer bufferRes = null;
        TrustManager[] tm = { new MyX509TrustManager() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory  
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        URL urlGet = new URL(url);
        http = (HttpsURLConnection) urlGet.openConnection();
        // 
        http.setConnectTimeout(TIME_OUT_CONNECT);
        // ? --??
        http.setReadTimeout(TIME_OUT_READ);
        http.setRequestMethod("POST");
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        http.setSSLSocketFactory(ssf);
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();

        out = http.getOutputStream();
        out.write(params.getBytes("UTF-8"));
        out.flush();

        in = http.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
        String valueString = null;
        bufferRes = new StringBuffer();
        while ((valueString = read.readLine()) != null) {
            bufferRes.append(valueString);
        }

        return bufferRes.toString();

    } catch (Exception e) {
        logger.error(String.format("HTTP POST url=[%s] param=[%s] due to fail.", url, params), e);
    } finally {

        if (null != out) {
            try {
                out.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP POST url=[%s] param=[%s]  close outputstream due to fail.",
                        url, params), e);
            }
        }
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP POST url=[%s] param=[%s] close inputstream due to fail.", url,
                        params), e);
            }
        }

        if (http != null) {
            // 
            http.disconnect();

        }
    }
    return StringUtils.EMPTY;
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?Https//w  w w .ja v  a 2  s. com
 *
 * @param requestUrl    ?
 * @param requestMethod ?
 * @param trustManagers ??
 * @param outputJson    ?
 * @return 
 */
public static String doHttpsRequest(String requestUrl, String requestMethod, TrustManager[] trustManagers,
        String outputJson) {
    String result = null;
    try {
        StringBuffer buffer = new StringBuffer();
        // SSLContext??
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, trustManagers, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory
        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);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        // ????
        if (null != outputJson) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
            //??
            outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
            outputStream.close();
        }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("Weixin server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("https request error:", e);
    } finally {
        return result;
    }
}

From source file:com.glaf.core.util.http.HttpUtils.java

/**
 * ?https?//from   w w w. j  a  v  a 2s .com
 * 
 * @param requestUrl
 *            ?
 * @param method
 *            ?GET?POST
 * @param content
 *            ???
 * @return
 */
public static String doRequest(String requestUrl, String method, String content, boolean isSSL) {
    log.debug("requestUrl:" + requestUrl);
    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    BufferedReader bufferedReader = null;
    InputStreamReader inputStreamReader = null;
    StringBuffer buffer = new StringBuffer();
    try {
        URL url = new URL(requestUrl);
        conn = (HttpsURLConnection) url.openConnection();
        if (isSSL) {
            // SSLContext??
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // SSLContextSSLSocketFactory
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            conn.setSSLSocketFactory(ssf);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // ?GET/POST
        conn.setRequestMethod(method);
        if ("GET".equalsIgnoreCase(method)) {
            conn.connect();
        }

        // ????
        if (StringUtils.isNotEmpty(content)) {
            OutputStream outputStream = conn.getOutputStream();
            // ????
            outputStream.write(content.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
        }

        // ???
        inputStream = conn.getInputStream();
        inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }

        log.debug("response:" + buffer.toString());

    } catch (ConnectException ce) {
        ce.printStackTrace();
        log.error(" http server connection timed out.");
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("http request error:{}", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(inputStreamReader);
        if (conn != null) {
            conn.disconnect();
        }
    }
    return buffer.toString();
}

From source file:com.ct855.util.HttpsClientUtil.java

public static String getUrl(String url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();

    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setRequestProperty("Ocp-Apim-Subscription-Key", "d8400b4cdf104015bb23d7fe847352c8");
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);//from w  ww. ja va2  s.c o m
    aConnection.setDoInput(true);
    aConnection.setRequestMethod("GET");

    InputStream resultStream = aConnection.getInputStream();
    BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
    StringBuffer aResponse = new StringBuffer();
    String aLine = aReader.readLine();
    while (aLine != null) {
        aResponse.append(aLine + "\n");
        aLine = aReader.readLine();
    }
    resultStream.close();
    return aResponse.toString();
}