Search in sources :

Example 66 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project portal by ixinportal.

the class WeixinUtil1 method httpRequest.

/**
 * 发起https请求并获取结果
 *
 * @param requestUrl 请求地址
 * @param requestMethod 请求方式(GET、POST)
 * @param outputStr 提交的数据
 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
 */
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
    JSONObject jsonObject = null;
    StringBuffer buffer = new StringBuffer();
    try {
        // 创建SSLContext对象,并使用我们指定的信任管理器初始化
        TrustManager[] tm = { new MX509TrustManager() };
        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 = JSON.parseObject(buffer.toString());
    } catch (ConnectException ce) {
        log.error("Weixin server connection timed out.");
    } catch (Exception e) {
        log.error("https request error:{}", e);
    }
    return jsonObject;
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) SSLContext(javax.net.ssl.SSLContext) URL(java.net.URL) JSONException(com.alibaba.fastjson.JSONException) ConnectException(java.net.ConnectException) TrustManager(javax.net.ssl.TrustManager) JSONObject(com.alibaba.fastjson.JSONObject) BufferedReader(java.io.BufferedReader) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) ConnectException(java.net.ConnectException)

Example 67 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project incubator-servicecomb-java-chassis by apache.

the class SSLManager method createSSLSocketFactory.

public static SSLSocketFactory createSSLSocketFactory(SSLOption option, SSLCustom custom) {
    SSLContext context = createSSLContext(option, custom);
    SSLSocketFactory factory = context.getSocketFactory();
    String[] supported = factory.getSupportedCipherSuites();
    String[] eanbled = option.getCiphers().split(",");
    return new SSLSocketFactoryExt(factory, getEnabledCiphers(supported, eanbled), option.getProtocols().split(","));
}
Also used : SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 68 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project incubator-servicecomb-java-chassis by apache.

the class SSLManager method createSSLSocket.

public static SSLSocket createSSLSocket(SSLOption option, SSLCustom custom) {
    try {
        SSLContext context = createSSLContext(option, custom);
        SSLSocketFactory facroty = context.getSocketFactory();
        SSLSocket socket = (SSLSocket) facroty.createSocket();
        socket.setEnabledProtocols(option.getProtocols().split(","));
        String[] supported = socket.getSupportedCipherSuites();
        String[] eanbled = option.getCiphers().split(",");
        socket.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled));
        return socket;
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException("unkown host");
    } catch (IOException e) {
        throw new IllegalArgumentException("unable create socket");
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) SSLSocket(javax.net.ssl.SSLSocket) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 69 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project data-transfer-project by google.

the class TestHelper method createTestBuilder.

/**
 * Creates an OKHttpClient.Builder that accepts self-signd certs from a host and Microsoft
 * domains.
 */
public static OkHttpClient.Builder createTestBuilder(String host) throws Exception {
    TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

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

        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }
    } };
    X509TrustManager x509TrustManager = new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

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

        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }
    };
    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
    SSLContext sslContext = SSLContext.getInstance("SSL");
    SecureRandom secureRandom = new SecureRandom();
    sslContext.init(null, trustManagers, secureRandom);
    SSLSocketFactory socketFactory = sslContext.getSocketFactory();
    clientBuilder.sslSocketFactory(socketFactory, x509TrustManager);
    HostnameVerifier hostnameVerifier = (hostname, session) -> host.equals(hostname) || hostname.endsWith("microsoftonline.com") || hostname.endsWith("microsoft.com");
    clientBuilder.hostnameVerifier(hostnameVerifier);
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    clientBuilder.addInterceptor(logging);
    return clientBuilder;
}
Also used : SecureRandom(java.security.SecureRandom) X509Certificate(java.security.cert.X509Certificate) SSLContext(javax.net.ssl.SSLContext) OkHttpClient(okhttp3.OkHttpClient) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManager(javax.net.ssl.TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) OkHttpClient(okhttp3.OkHttpClient) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManager(javax.net.ssl.TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor)

Example 70 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project libsignal-service-java by signalapp.

the class WebSocketConnection method connect.

public synchronized void connect() {
    Log.w(TAG, "WSC connect()...");
    if (client == null) {
        String filledUri = String.format(wsUri, credentialsProvider.getUser(), credentialsProvider.getPassword());
        Pair<SSLSocketFactory, X509TrustManager> socketFactory = createTlsSocketFactory(trustStore);
        OkHttpClient okHttpClient = new OkHttpClient.Builder().sslSocketFactory(socketFactory.first(), socketFactory.second()).readTimeout(KEEPALIVE_TIMEOUT_SECONDS + 10, TimeUnit.SECONDS).connectTimeout(KEEPALIVE_TIMEOUT_SECONDS + 10, TimeUnit.SECONDS).build();
        Request.Builder requestBuilder = new Request.Builder().url(filledUri);
        if (userAgent != null) {
            requestBuilder.addHeader("X-Signal-Agent", userAgent);
        }
        if (listener != null) {
            listener.onConnecting();
        }
        this.connected = false;
        this.client = okHttpClient.newWebSocket(requestBuilder.build(), this);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) X509TrustManager(javax.net.ssl.X509TrustManager) Request(okhttp3.Request) ByteString(okio.ByteString) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Aggregations

SSLSocketFactory (javax.net.ssl.SSLSocketFactory)403 SSLContext (javax.net.ssl.SSLContext)150 SSLSocket (javax.net.ssl.SSLSocket)134 IOException (java.io.IOException)106 X509TrustManager (javax.net.ssl.X509TrustManager)69 Socket (java.net.Socket)63 TrustManager (javax.net.ssl.TrustManager)56 HostnameVerifier (javax.net.ssl.HostnameVerifier)49 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)48 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)48 Test (org.junit.Test)46 KeyManagementException (java.security.KeyManagementException)45 URL (java.net.URL)41 CertificateException (java.security.cert.CertificateException)39 OkHttpClient (okhttp3.OkHttpClient)39 OutputStream (java.io.OutputStream)35 InputStream (java.io.InputStream)34 X509Certificate (java.security.cert.X509Certificate)34 SSLSession (javax.net.ssl.SSLSession)30 InetSocketAddress (java.net.InetSocketAddress)29