Search in sources :

Example 96 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project countly-sdk-js by Countly.

the class ConnectionProcessor method urlConnectionForEventData.

URLConnection urlConnectionForEventData(final String eventData) throws IOException {
    String urlStr = serverURL_ + "/i?";
    if (!eventData.contains("&crash=") && eventData.length() < 2048) {
        urlStr += eventData;
        urlStr += "&checksum=" + sha1Hash(eventData + salt);
    } else {
        urlStr += "checksum=" + sha1Hash(eventData + salt);
    }
    final URL url = new URL(urlStr);
    final HttpURLConnection conn;
    if (Countly.publicKeyPinCertificates == null && Countly.certificatePinCertificates == null) {
        conn = (HttpURLConnection) url.openConnection();
    } else {
        HttpsURLConnection c = (HttpsURLConnection) url.openConnection();
        c.setSSLSocketFactory(sslContext_.getSocketFactory());
        conn = c;
    }
    conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS);
    conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS);
    conn.setUseCaches(false);
    conn.setDoInput(true);
    conn.setRequestMethod("GET");
    String picturePath = UserData.getPicturePathFromQuery(url);
    if (Countly.sharedInstance().isLoggingEnabled()) {
        Log.d(Countly.TAG, "Got picturePath: " + picturePath);
    }
    if (Countly.sharedInstance().isLoggingEnabled()) {
        Log.v(Countly.TAG, "Is the HTTP POST forced: " + Countly.sharedInstance().isHttpPostForced());
    }
    if (!picturePath.equals("")) {
        // Uploading files:
        // http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests
        File binaryFile = new File(picturePath);
        conn.setDoOutput(true);
        // Just generate some unique random value.
        String boundary = Long.toHexString(System.currentTimeMillis());
        // Line separator required by multipart/form-data.
        String CRLF = "\r\n";
        String charset = "UTF-8";
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        OutputStream output = conn.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
        // Send binary file.
        writer.append("--").append(boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"").append(binaryFile.getName()).append("\"").append(CRLF);
        writer.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
        writer.append("Content-Transfer-Encoding: binary").append(CRLF);
        writer.append(CRLF).flush();
        FileInputStream fileInputStream = new FileInputStream(binaryFile);
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = fileInputStream.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        // Important before continuing with writer!
        output.flush();
        // CRLF is important! It indicates end of boundary.
        writer.append(CRLF).flush();
        fileInputStream.close();
        // End of multipart/form-data.
        writer.append("--").append(boundary).append("--").append(CRLF).flush();
    } else {
        if (eventData.contains("&crash=") || eventData.length() >= 2048 || Countly.sharedInstance().isHttpPostForced()) {
            if (Countly.sharedInstance().isLoggingEnabled()) {
                Log.d(Countly.TAG, "Using HTTP POST");
            }
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(eventData);
            writer.flush();
            writer.close();
            os.close();
        } else {
            if (Countly.sharedInstance().isLoggingEnabled()) {
                Log.d(Countly.TAG, "Using HTTP GET");
            }
            conn.setDoOutput(false);
        }
    }
    return conn;
}
Also used : OutputStream(java.io.OutputStream) IOException(java.io.IOException) URL(java.net.URL) FileInputStream(java.io.FileInputStream) BufferedWriter(java.io.BufferedWriter) HttpURLConnection(java.net.HttpURLConnection) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) PrintWriter(java.io.PrintWriter)

Example 97 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project vip by guangdada.

the class HttpUtil method get.

public static String get(String url) {
    String result = null;
    try {
        // 设置SSLContext
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[] { myX509TrustManager }, null);
        // 打开连接
        // 要发送的POST请求url?Key=Value&amp;Key2=Value2&amp;Key3=Value3的形式
        URL requestUrl = new URL(url);
        HttpsURLConnection httpsConn = (HttpsURLConnection) requestUrl.openConnection();
        // 设置套接工厂
        httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
        // 加入数据
        httpsConn.setRequestMethod("GET");
        // httpsConn.setDoOutput(true);
        // 获取输入流
        BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
        int code = httpsConn.getResponseCode();
        if (HttpsURLConnection.HTTP_OK == code) {
            String temp = in.readLine();
            /* 连接成一个字符串 */
            while (temp != null) {
                if (result != null)
                    result += temp;
                else
                    result = temp;
                temp = in.readLine();
            }
        }
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}
Also used : ProtocolException(java.net.ProtocolException) MalformedURLException(java.net.MalformedURLException) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) KeyManagementException(java.security.KeyManagementException)

Example 98 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project box-android-sdk by box.

the class BoxRequest method onSend.

/**
 * Synchronously make the request to Box and handle the response appropriately.
 * @return the expected BoxObject if the request is successful.
 * @throws BoxException thrown if there was a problem with handling the request.
 */
protected T onSend() throws BoxException {
    BoxRequest.BoxRequestHandler requestHandler = getRequestHandler();
    BoxHttpResponse response = null;
    HttpURLConnection connection = null;
    try {
        // Create the HTTP request and send it
        BoxHttpRequest request = createHttpRequest();
        connection = request.getUrlConnection();
        if (mRequiresSocket && connection instanceof HttpsURLConnection) {
            final SSLSocketFactory factory = ((HttpsURLConnection) connection).getSSLSocketFactory();
            SSLSocketFactoryWrapper wrappedFactory = new SSLSocketFactoryWrapper(factory);
            mSocketFactoryRef = new WeakReference<SSLSocketFactoryWrapper>(wrappedFactory);
            ((HttpsURLConnection) connection).setSSLSocketFactory(wrappedFactory);
        }
        if (mTimeout > 0) {
            connection.setConnectTimeout(mTimeout);
            connection.setReadTimeout(mTimeout);
        }
        response = sendRequest(request, connection);
        logDebug(response);
        // Process the response through the provided handler
        if (requestHandler.isResponseSuccess(response)) {
            T result = (T) requestHandler.onResponse(mClazz, response);
            return result;
        }
        throw new BoxException("An error occurred while sending the request", response);
    } catch (IOException e) {
        return handleSendException(requestHandler, response, e);
    } catch (InstantiationException e) {
        return handleSendException(requestHandler, response, e);
    } catch (IllegalAccessException e) {
        return handleSendException(requestHandler, response, e);
    } catch (BoxException e) {
        return handleSendException(requestHandler, response, e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}
Also used : BoxException(com.box.androidsdk.content.BoxException) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 99 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project openmeetings by apache.

the class SignInPage method prepareConnection.

private void prepareConnection(URLConnection _connection) {
    if (!(_connection instanceof HttpsURLConnection)) {
        return;
    }
    if (!cfgDao.getBool(CONFIG_IGNORE_BAD_SSL, false)) {
        return;
    }
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        // no-op
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        // no-op
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    } };
    try {
        HttpsURLConnection connection = (HttpsURLConnection) _connection;
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        connection.setSSLSocketFactory(sslSocketFactory);
        connection.setHostnameVerifier((arg0, arg1) -> true);
    } catch (Exception e) {
        log.error("[prepareConnection]", e);
    }
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) X509Certificate(java.security.cert.X509Certificate) RedirectToUrlException(org.apache.wicket.request.flow.RedirectToUrlException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) OmException(org.apache.openmeetings.util.OmException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JSONException(com.github.openjson.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 100 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project AnyMemo by helloworld1.

the class SpreadsheetFactory method getSpreadsheets.

public static List<Spreadsheet> getSpreadsheets(String authToken) throws XmlPullParserException, IOException {
    URL url = new URL("https://spreadsheets.google.com/feeds/spreadsheets/private/full?access_token=" + authToken);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    if (conn.getResponseCode() / 100 >= 3) {
        String s = new String(IOUtils.toByteArray(conn.getErrorStream()));
        throw new IOException(s);
    }
    List<Spreadsheet> spreadsheetList = EntryFactory.getEntries(Spreadsheet.class, conn.getInputStream());
    return spreadsheetList;
}
Also used : IOException(java.io.IOException) URL(java.net.URL) 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