Example usage for javax.net.ssl HttpsURLConnection setSSLSocketFactory

List of usage examples for javax.net.ssl HttpsURLConnection setSSLSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setSSLSocketFactory.

Prototype

public void setSSLSocketFactory(SSLSocketFactory sf) 

Source Link

Document

Sets the <code>SSLSocketFactory</code> to be used when this instance creates sockets for secure https URL connections.

Usage

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

/**
 * ?Https//from w w w  .ja  va 2s .c om
 *
 * @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:org.apache.atlas.security.SecureClientUtils.java

public static URLConnectionClientHandler getUrlConnectionClientHandler() {
    return new URLConnectionClientHandler(new HttpURLConnectionFactory() {
        @Override//from  w w w  . j  av a2  s .c o  m
        public HttpURLConnection getHttpURLConnection(URL url) throws IOException {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            if (connection instanceof HttpsURLConnection) {
                LOG.debug("Attempting to configure HTTPS connection using client " + "configuration");
                final SSLFactory factory;
                final SSLSocketFactory sf;
                final HostnameVerifier hv;

                try {
                    Configuration conf = new Configuration();
                    conf.addResource(
                            conf.get(SSLFactory.SSL_CLIENT_CONF_KEY, SecurityProperties.SSL_CLIENT_PROPERTIES));
                    UserGroupInformation.setConfiguration(conf);

                    HttpsURLConnection c = (HttpsURLConnection) connection;
                    factory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
                    factory.init();
                    sf = factory.createSSLSocketFactory();
                    hv = factory.getHostnameVerifier();
                    c.setSSLSocketFactory(sf);
                    c.setHostnameVerifier(hv);
                } catch (Exception e) {
                    LOG.info("Unable to configure HTTPS connection from "
                            + "configuration.  Leveraging JDK properties.");
                }
            }
            return connection;
        }
    });
}

From source file:com.foxykeep.datadroid.internal.network.NetworkConnectionImpl.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./*from w  w w. j a va  2  s  .  c  o m*/
 *
 * @param context The context to use for this operation. Used to generate the user agent if
 *            needed.
 * @param urlValue The webservice URL.
 * @param method The request method to use.
 * @param parameterList The parameters to add to the request.
 * @param headerMap The headers to add to the request.
 * @param isGzipEnabled Whether the request will use gzip compression if available on the
 *            server.
 * @param userAgent The user agent to set in the request. If null, a default Android one will be
 *            created.
 * @param postText The POSTDATA text to add in the request.
 * @param credentials The credentials to use for authentication.
 * @param isSslValidationEnabled Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled) throws ConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // Log the request
        if (DataDroidLog.canLog(Log.DEBUG)) {
            DataDroidLog.d(TAG, "Request url: " + urlValue);
            DataDroidLog.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                DataDroidLog.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    DataDroidLog.d(TAG, message);
                }

                DataDroidLog.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                DataDroidLog.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                DataDroidLog.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = postText;
            }
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(outputText.getBytes());
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing to do here.
                    }
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        DataDroidLog.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String error = convertStreamToString(errorStream, isGzip);
            throw new ConnectionException(error, responseCode);
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip);

        if (DataDroidLog.canLog(Log.VERBOSE)) {
            DataDroidLog.v(TAG, "Response body: ");

            int pos = 0;
            int bodyLength = body.length();
            while (pos < bodyLength) {
                DataDroidLog.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200)));
                pos = pos + 200;
            }
        }

        return new ConnectionResult(connection.getHeaderFields(), body);
    } catch (IOException e) {
        DataDroidLog.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        DataDroidLog.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        DataDroidLog.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.phicomm.account.network.NetworkConnectionImpl.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./*from w w  w  .  j av a 2s.  c  om*/
 *
 * @param context The context to use for this operation. Used to generate the user agent if
 *            needed.
 * @param urlValue The webservice URL.
 * @param method The request method to use.
 * @param parameterList The parameters to add to the request.
 * @param headerMap The headers to add to the request.
 * @param isGzipEnabled Whether the request will use gzip compression if available on the
 *            server.
 * @param userAgent The user agent to set in the request. If null, a default Android one will be
 *            created.
 * @param postText The POSTDATA text to add in the request.
 * @param credentials The credentials to use for authentication.
 * @param isSslValidationEnabled Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled) throws ConnectionException {
    Thread.dumpStack();
    Log.i("ss", "NetworkConnectionImpl_____________________________________execute__urlValue:" + urlValue);
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // Log the request
        if (true) {
            Log.d(TAG, "Request url: " + urlValue);
            Log.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                Log.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    Log.d(TAG, message);
                }

                Log.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                Log.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                Log.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    Log.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = HttpUrlConnectionHelper.openUrlConnection(url);
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = postText;
            }
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(outputText.getBytes());
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing to do here.
                    }
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        Log.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String error = convertStreamToString(errorStream, isGzip);
            throw new ConnectionException(error, responseCode);
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip);

        if (true) {
            Log.v(TAG, "Response body: ");

            int pos = 0;
            int bodyLength = body.length();
            while (pos < bodyLength) {
                Log.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200)));
                pos = pos + 200;
            }
        }

        return new ConnectionResult(connection.getHeaderFields(), body);
    } catch (IOException e) {
        Log.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        Log.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.foxykeep.datadroid.internal.network.NetworkConnectionImplF.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result.//from  ww w . ja v a2s  . co m
 *
 * @param context The context to use for this operation. Used to generate the user agent if
 *            needed.
 * @param urlValue The webservice URL.
 * @param method The request method to use.
 * @param parameterList The parameters to add to the request.
 * @param headerMap The headers to add to the request.
 * @param isGzipEnabled Whether the request will use gzip compression if available on the
 *            server.
 * @param userAgent The user agent to set in the request. If null, a default Android one will be
 *            created.
 * @param postText The POSTDATA text to add in the request.
 * @param credentials The credentials to use for authentication.
 * @param isSslValidationEnabled Whether the request will validate the SSL certificates.
 * @return The result of the webservice call.
 */
public static ConnectionResult execute(Context context, String urlValue, Method method,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled, File file) throws ConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // Log the request
        if (DataDroidLog.canLog(Log.DEBUG)) {
            DataDroidLog.d(TAG, "Request url: " + urlValue);
            DataDroidLog.d(TAG, "Method: " + method.toString());

            if (parameterList != null && !parameterList.isEmpty()) {
                DataDroidLog.d(TAG, "Parameters:");
                for (int i = 0, size = parameterList.size(); i < size; i++) {
                    BasicNameValuePair parameter = parameterList.get(i);
                    String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                    DataDroidLog.d(TAG, message);
                }

                DataDroidLog.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
            }

            if (postText != null) {
                DataDroidLog.d(TAG, "Post data: " + postText);
            }

            if (headerMap != null && !headerMap.isEmpty()) {
                DataDroidLog.d(TAG, "Headers:");
                for (Entry<String, String> header : headerMap.entrySet()) {
                    DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue());
                }
            }
        }

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = (HttpURLConnection) url.openConnection();
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = postText;
            }
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(READ_OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(outputText.getBytes());
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing to do here.
                    }
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        DataDroidLog.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            throw new ConnectionException("error", responseCode);
        }

        String body = convertStreamToString(connection.getInputStream(), isGzip, file, context);

        return new ConnectionResult(connection.getHeaderFields(), body);
    } catch (IOException e) {
        DataDroidLog.e(TAG, "IOException", e);
        throw new ConnectionException(e);
    } catch (KeyManagementException e) {
        DataDroidLog.e(TAG, "KeyManagementException", e);
        throw new ConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        DataDroidLog.e(TAG, "NoSuchAlgorithmException", e);
        throw new ConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.aware.ui.Plugins_Manager.java

/**
* Downloads and compresses image for optimized icon caching
* @param image_url//from   w  w  w  .  java2 s .  c o  m
* @return
*/
public static byte[] cacheImage(String image_url, Context sContext) {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = sContext.getResources().openRawResource(R.raw.aware);
        Certificate ca;
        try {
            ca = cf.generateCertificate(caInput);
        } finally {
            caInput.close();
        }

        KeyStore sKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream inStream = sContext.getResources().openRawResource(R.raw.awareframework);
        sKeyStore.load(inStream, "awareframework".toCharArray());
        inStream.close();

        sKeyStore.setCertificateEntry("ca", ca);

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(sKeyStore);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        //Fetch image now that we recognise SSL
        URL image_path = new URL(image_url.replace("http://", "https://")); //make sure we are fetching the images over https
        HttpsURLConnection image_connection = (HttpsURLConnection) image_path.openConnection();
        image_connection.setSSLSocketFactory(context.getSocketFactory());

        InputStream in_stream = image_connection.getInputStream();
        Bitmap tmpBitmap = BitmapFactory.decodeStream(in_stream);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        tmpBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);

        return output.toByteArray();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.sckftr.android.utils.net.Network.java

/**
 * Call the webservice using the given parameters to construct the request and return the
 * result./*from w w  w  . ja  v a  2s.c om*/
 *
 *
 * @param context The context to use for this operation. Used to generate the user agent if
 *            needed.
 * @param urlValue The webservice URL.
 * @param method The request method to use.
 * @param handler
 *@param parameterList The parameters to add to the request.
 * @param headerMap The headers to add to the request.
 * @param isGzipEnabled Whether the request will use gzip compression if available on the
*            server.
 * @param userAgent The user agent to set in the request. If null, a default Android one will be
*            created.
 * @param postText The POSTDATA text to add in the request.
 * @param credentials The credentials to use for authentication.
 * @param isSslValidationEnabled Whether the request will validate the SSL certificates.        @return The result of the webservice call.
 */
static <Out> Out execute(Context context, String urlValue, Method method, Executor<BufferedReader, Out> handler,
        ArrayList<BasicNameValuePair> parameterList, HashMap<String, String> headerMap, boolean isGzipEnabled,
        String userAgent, String postText, UsernamePasswordCredentials credentials,
        boolean isSslValidationEnabled) throws NetworkConnectionException {
    HttpURLConnection connection = null;
    try {
        // Prepare the request information
        if (userAgent == null) {
            userAgent = UserAgentUtils.get(context);
        }
        if (headerMap == null) {
            headerMap = new HashMap<String, String>();
        }
        headerMap.put(HTTP.USER_AGENT, userAgent);
        if (isGzipEnabled) {
            headerMap.put(ACCEPT_ENCODING_HEADER, "gzip");
        }
        headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET);
        if (credentials != null) {
            headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials));
        }

        StringBuilder paramBuilder = new StringBuilder();
        if (parameterList != null && !parameterList.isEmpty()) {
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String name = parameter.getName();
                String value = parameter.getValue();
                if (TextUtils.isEmpty(name)) {
                    // Empty parameter name. Check the next one.
                    continue;
                }
                if (value == null) {
                    value = "";
                }
                paramBuilder.append(URLEncoder.encode(name, UTF8_CHARSET));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(value, UTF8_CHARSET));
                paramBuilder.append("&");
            }
        }

        // Log the request
        //if (Log.canLog(Log.DEBUG)) {
        Log.d(TAG, method.toString() + ": " + urlValue);

        if (parameterList != null && !parameterList.isEmpty()) {
            //Log.d(TAG, "Parameters:");
            for (int i = 0, size = parameterList.size(); i < size; i++) {
                BasicNameValuePair parameter = parameterList.get(i);
                String message = "- \"" + parameter.getName() + "\" = \"" + parameter.getValue() + "\"";
                Log.d(TAG, message);
            }

            //Log.d(TAG, "Parameters String: \"" + paramBuilder.toString() + "\"");
        }

        if (postText != null) {
            Log.d(TAG, "Post data: " + postText);
        }

        if (headerMap != null && !headerMap.isEmpty()) {
            //Log.d(TAG, "Headers:");
            for (Entry<String, String> header : headerMap.entrySet()) {
                //Log.d(TAG, "- " + header.getKey() + " = " + header.getValue());
            }
        }
        //}

        // Create the connection object
        URL url = null;
        String outputText = null;
        switch (method) {
        case GET:
        case DELETE:
            String fullUrlValue = urlValue;
            if (paramBuilder.length() > 0) {
                fullUrlValue += "?" + paramBuilder.toString();
            }
            url = new URL(fullUrlValue);
            connection = (HttpURLConnection) url.openConnection();
            break;
        case PUT:
        case POST:
            url = new URL(urlValue);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);

            if (paramBuilder.length() > 0) {
                outputText = paramBuilder.toString();
                headerMap.put(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
                headerMap.put(HTTP.CONTENT_LEN, String.valueOf(outputText.getBytes().length));
            } else if (postText != null) {
                outputText = postText;
            }
            break;
        }

        // Set the request method
        connection.setRequestMethod(method.toString());

        // If it's an HTTPS request and the SSL Validation is disabled
        if (url.getProtocol().equals("https") && !isSslValidationEnabled) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory());
            httpsConnection.setHostnameVerifier(getAllHostsValidVerifier());
        }

        // Add the headers
        if (!headerMap.isEmpty()) {
            for (Entry<String, String> header : headerMap.entrySet()) {
                connection.addRequestProperty(header.getKey(), header.getValue());
            }
        }

        // Set the connection and read timeout
        connection.setConnectTimeout(OPERATION_TIMEOUT);
        connection.setReadTimeout(OPERATION_TIMEOUT);

        // Set the outputStream content for POST and PUT requests
        if ((method == Method.POST || method == Method.PUT) && outputText != null) {
            OutputStream output = null;
            try {
                output = connection.getOutputStream();
                output.write(outputText.getBytes());
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        // Already catching the first IOException so nothing to do here.
                    }
                }
            }
        }

        String contentEncoding = connection.getHeaderField(HTTP.CONTENT_ENCODING);

        int responseCode = connection.getResponseCode();
        boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip");
        Log.d(TAG, "Response code: " + responseCode);

        if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            String redirectionUrl = connection.getHeaderField(LOCATION_HEADER);
            throw new NetworkConnectionException("New location : " + redirectionUrl, redirectionUrl);
        }

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            String err = evaluateStream(errorStream, new StringReaderHandler(), isGzip);
            throw new NetworkConnectionException(err, responseCode);
        }

        return evaluateStream(connection.getInputStream(), handler, isGzip);

    } catch (IOException e) {
        Log.e(TAG, "IOException", e);
        throw new NetworkConnectionException(e);
    } catch (KeyManagementException e) {
        Log.e(TAG, "KeyManagementException", e);
        throw new NetworkConnectionException(e);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "NoSuchAlgorithmException", e);
        throw new NetworkConnectionException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.simiacryptus.util.Util.java

/**
 * Cache input stream.//  w  w w  .java 2  s  .co m
 *
 * @param url  the url
 * @param file the file
 * @return the input stream
 * @throws IOException              the io exception
 * @throws NoSuchAlgorithmException the no such algorithm exception
 * @throws KeyStoreException        the key store exception
 * @throws KeyManagementException   the key management exception
 */
public static InputStream cache(String url, String file)
        throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    if (new File(file).exists()) {
        return new FileInputStream(file);
    } else {
        TrustManager[] trustManagers = { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, trustManagers, null);
        SSLSocketFactory sslFactory = ctx.getSocketFactory();
        URLConnection urlConnection = new URL(url).openConnection();
        if (urlConnection instanceof javax.net.ssl.HttpsURLConnection) {
            HttpsURLConnection conn = (HttpsURLConnection) urlConnection;
            conn.setSSLSocketFactory(sslFactory);
            conn.setRequestMethod("GET");
        }
        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream cache = new FileOutputStream(file);
        return new TeeInputStream(inputStream, cache);
    }
}

From source file:com.camel.trainreserve.JDKHttpsClient.java

public static String doPost(String url, String cookieStr, String ctype, byte[] content, int connectTimeout,
        int readTimeout) throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;//from w ww .j ava  2  s.  c om
    String rsp = null;
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            //SSLContext.setDefault(ctx);
            conn = getConnection(new URL(url), METHOD_POST, ctype);
            conn.setSSLSocketFactory(ctx.getSocketFactory());

            conn.setRequestProperty("Cookie", cookieStr);
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
        } catch (Exception e) {
            log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
            throw e;
        }
        try {
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java

/**
 *
 * @param urlConn//from  w w w. j  a  v  a  2  s . c o  m
 * @param sslVerify
 * @param hostnameVerify
 * @param trustCertFactory
 * @param clientKeyFactory
 */
private static void setSSLSocketFactory(HttpURLConnection urlConn, boolean sslVerify, boolean hostnameVerify,
        TrustKeyStore trustCertFactory, ClientKeyStore clientKeyFactory) {
    try {
        SSLSocketFactory socketFactory = null;
        if (trustCertFactory != null || clientKeyFactory != null || !sslVerify) {
            SSLContext sc = SSLContext.getInstance("SSL");
            TrustManager[] trustManagers = null;
            KeyManager[] keyManagers = null;
            if (trustCertFactory != null) {
                trustManagers = trustCertFactory.getTrustManagerFactory().getTrustManagers();
            }
            if (clientKeyFactory != null) {
                keyManagers = clientKeyFactory.getKeyManagerFactory().getKeyManagers();
            }
            if (!sslVerify) {
                trustManagers = trustAnyManagers;
                hostnameVerify = false;
            }
            sc.init(keyManagers, trustManagers, new java.security.SecureRandom());
            socketFactory = sc.getSocketFactory();
        }

        if (urlConn instanceof HttpsURLConnection) {
            HttpsURLConnection httpsUrlCon = (HttpsURLConnection) urlConn;
            if (socketFactory != null) {
                httpsUrlCon.setSSLSocketFactory(socketFactory);
            }
            //??hostname
            if (!hostnameVerify) {
                httpsUrlCon.setHostnameVerifier(new TrustAnyHostnameVerifier());
            }
        }
        if (urlConn instanceof com.sun.net.ssl.HttpsURLConnection) {
            com.sun.net.ssl.HttpsURLConnection httpsUrlCon = (com.sun.net.ssl.HttpsURLConnection) urlConn;
            if (socketFactory != null) {
                httpsUrlCon.setSSLSocketFactory(socketFactory);
            }
            //??hostname
            if (!hostnameVerify) {
                httpsUrlCon.setHostnameVerifier(new TrustAnyHostnameVerifierOld());
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}