Search in sources :

Example 76 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project wso2-synapse by wso2.

the class SynapseConfigUtils method getURLConnection.

/**
 * Returns a URLCOnnection for given URL. If the URL is https one , then URLConnectin is a
 * HttpsURLCOnnection and it is configured with KeyStores given in the synapse.properties file
 *
 * @param url URL
 * @return URLConnection for given URL
 */
public static URLConnection getURLConnection(URL url) {
    try {
        if (url == null) {
            if (log.isDebugEnabled()) {
                log.debug("Provided URL is null");
            }
            return null;
        }
        URLConnection connection;
        if (url.getProtocol().equalsIgnoreCase("http") || url.getProtocol().equalsIgnoreCase("https")) {
            Properties synapseProperties = SynapsePropertiesLoader.loadSynapseProperties();
            String proxyHost = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_HOST);
            String proxyPort = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_PORT);
            // get the list of excluded hosts for proxy
            List<String> excludedHosts = getExcludedHostsForProxy(synapseProperties);
            if (proxyHost != null && proxyPort != null && !excludedHosts.contains(proxyHost)) {
                SocketAddress sockaddr = new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort));
                Proxy proxy = new Proxy(Proxy.Type.HTTP, sockaddr);
                if (url.getProtocol().equalsIgnoreCase("https")) {
                    connection = getHttpsURLConnection(url, synapseProperties, proxy);
                } else {
                    connection = url.openConnection(proxy);
                }
            } else {
                if (url.getProtocol().equalsIgnoreCase("https")) {
                    connection = getHttpsURLConnection(url, synapseProperties, null);
                } else {
                    connection = url.openConnection();
                }
            }
            // try to see weather authentication is required
            String userName = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_USER);
            String password = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_PASSWORD);
            if (userName != null && password != null) {
                String header = userName + ":" + password;
                byte[] encodedHeaderBytes = new Base64().encode(header.getBytes());
                String encodedHeader = new String(encodedHeaderBytes);
                connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedHeader);
            }
        } else {
            connection = url.openConnection();
        }
        connection.setReadTimeout(getReadTimeout());
        connection.setConnectTimeout(getConnectTimeout());
        // if http is being used
        connection.setRequestProperty("Connection", "close");
        return connection;
    } catch (IOException e) {
        handleException("Error reading at URI ' " + url + " ' ", e);
    }
    return null;
}
Also used : Proxy(java.net.Proxy) Base64(org.apache.commons.codec.binary.Base64) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) Properties(java.util.Properties) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 77 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project wso2-synapse by wso2.

the class SynapseConfigUtils method getHttpsURLConnection.

/**
 * Helper method to create a HttpSURLConnection with provided KeyStores
 *
 * @param url Https URL
 * @param synapseProperties properties for extracting info
 * @param proxy if there is a proxy
 * @return gives out the connection created
 */
private static HttpsURLConnection getHttpsURLConnection(URL url, Properties synapseProperties, Proxy proxy) {
    if (log.isDebugEnabled()) {
        log.debug("Creating a HttpsURL Connection from given URL : " + url);
    }
    KeyManager[] keyManagers = null;
    TrustManager[] trustManagers = null;
    IdentityKeyStoreInformation identityInformation = KeyStoreInformationFactory.createIdentityKeyStoreInformation(synapseProperties);
    if (identityInformation != null) {
        KeyManagerFactory keyManagerFactory = identityInformation.getIdentityKeyManagerFactoryInstance();
        if (keyManagerFactory != null) {
            keyManagers = keyManagerFactory.getKeyManagers();
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("There is no private key entry store configuration." + " Will use JDK's default one");
        }
    }
    TrustKeyStoreInformation trustInformation = KeyStoreInformationFactory.createTrustKeyStoreInformation(synapseProperties);
    if (trustInformation != null) {
        TrustManagerFactory trustManagerFactory = trustInformation.getTrustManagerFactoryInstance();
        if (trustManagerFactory != null) {
            trustManagers = trustManagerFactory.getTrustManagers();
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("There is no trusted certificate store configuration." + " Will use JDK's default one");
        }
    }
    try {
        HttpsURLConnection connection;
        if (proxy != null) {
            connection = (HttpsURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpsURLConnection) url.openConnection();
        }
        // Create a SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);
        connection.setSSLSocketFactory(sslContext.getSocketFactory());
        if (trustInformation != null) {
            // Determine is it need to overwrite default Host Name verifier
            boolean enableHostnameVerifier = true;
            String value = trustInformation.getParameter(KeyStoreInformation.ENABLE_HOST_NAME_VERIFIER);
            if (value != null) {
                enableHostnameVerifier = Boolean.parseBoolean(value);
            }
            if (!enableHostnameVerifier) {
                if (log.isDebugEnabled()) {
                    log.debug("Overriding default HostName Verifier." + "HostName verification disabled");
                }
                connection.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {

                    public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
                        if (log.isTraceEnabled()) {
                            log.trace("HostName verification disabled");
                            log.trace("Host:   " + hostname);
                            log.trace("Peer Host:  " + session.getPeerHost());
                        }
                        return true;
                    }
                });
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Using default HostName verifier...");
                }
            }
        }
        return connection;
    } catch (NoSuchAlgorithmException e) {
        handleException("Error loading SSLContext ", e);
    } catch (KeyManagementException e) {
        handleException("Error initiation SSLContext with KeyManagers", e);
    } catch (IOException e) {
        handleException("Error opening a https connection from URL : " + url, e);
    }
    return null;
}
Also used : TrustKeyStoreInformation(org.wso2.securevault.definition.TrustKeyStoreInformation) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) SSLSession(javax.net.ssl.SSLSession) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) IdentityKeyStoreInformation(org.wso2.securevault.definition.IdentityKeyStoreInformation) HostnameVerifier(javax.net.ssl.HostnameVerifier) KeyManager(javax.net.ssl.KeyManager) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 78 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection 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 79 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project -Netflix-CS122B by cxk123.

the class VerifyUtils method verify.

public static boolean verify(String gRecaptchaResponse) {
    if (gRecaptchaResponse == null || gRecaptchaResponse.length() == 0) {
        return false;
    }
    try {
        URL verifyUrl = new URL(SITE_VERIFY_URL);
        // Open Connection to URL
        HttpsURLConnection conn = (HttpsURLConnection) verifyUrl.openConnection();
        // Add Request Header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0");
        conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        // Data will be sent to the server.
        String postParams = "secret=" + MyConstants.SECRET_KEY + "&response=" + gRecaptchaResponse;
        // Send Request
        conn.setDoOutput(true);
        // Get the output stream of Connection
        // Write data in this stream, which means to send data to Server.
        OutputStream outStream = conn.getOutputStream();
        outStream.write(postParams.getBytes());
        outStream.flush();
        outStream.close();
        // Response code return from server.
        int responseCode = conn.getResponseCode();
        System.out.println("responseCode=" + responseCode);
        // Get the InputStream from Connection to read data sent from the server.
        InputStream is = conn.getInputStream();
        JsonReader jsonReader = Json.createReader(is);
        JsonObject jsonObject = jsonReader.readObject();
        jsonReader.close();
        // ==> {"success": true}
        System.out.println("Response: " + jsonObject);
        boolean success = jsonObject.getBoolean("success");
        return success;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 80 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project SocialHelper by arvinljw.

the class SocialUtil method get.

static String get(URL url) throws Exception {
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    if (conn.getResponseCode() == 200) {
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while (-1 != (len = is.read(buffer))) {
            out.write(buffer, 0, len);
            out.flush();
        }
        return out.toString("utf-8");
    }
    return null;
}
Also used : InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Aggregations

HttpsURLConnection (javax.net.ssl.HttpsURLConnection)522 URL (java.net.URL)310 IOException (java.io.IOException)177 HttpURLConnection (java.net.HttpURLConnection)128 InputStreamReader (java.io.InputStreamReader)93 InputStream (java.io.InputStream)89 Test (org.junit.Test)83 BufferedReader (java.io.BufferedReader)78 SSLContext (javax.net.ssl.SSLContext)70 OutputStream (java.io.OutputStream)54 HostnameVerifier (javax.net.ssl.HostnameVerifier)50 MalformedURLException (java.net.MalformedURLException)48 URLConnection (java.net.URLConnection)47 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)47 ByteArrayOutputStream (java.io.ByteArrayOutputStream)46 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)37 HashMap (java.util.HashMap)34 DataOutputStream (java.io.DataOutputStream)32 KeyManagementException (java.security.KeyManagementException)32 JSONObject (org.json.JSONObject)29