Search in sources :

Example 76 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project runwar by cfmlprojects.

the class TestHttpClient method setSSLContext.

public void setSSLContext(final SSLContext sslContext) {
    SchemeRegistry registry = getConnectionManager().getSchemeRegistry();
    registry.unregister("https");
    if (DefaultServer.getHostAddress(DefaultServer.DEFAULT).equals("localhost")) {
        registry.register(new Scheme("https", 443, new SSLSocketFactory(sslContext)));
        registry.register(new Scheme("https", DefaultServer.getHostSSLPort("default"), new SSLSocketFactory(sslContext)));
    } else {
        registry.register(new Scheme("https", 443, new SSLSocketFactory(sslContext, NO_OP_VERIFIER)));
        registry.register(new Scheme("https", DefaultServer.getHostSSLPort("default"), new SSLSocketFactory(sslContext, NO_OP_VERIFIER)));
    }
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Example 77 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project playn by threerings.

the class AndroidHttpClient method newInstance.

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 *
 * @param userAgent to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent) {
    HttpParams params = new BasicHttpParams();
    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    // Default connection and socket timeout of 20 seconds. Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    // Don't handle redirects -- return them to the caller. Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);
    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicHttpParams(org.apache.http.params.BasicHttpParams) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager)

Example 78 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project Anki-Android by Ramblurr.

the class BasicHttpSyncer method req.

public HttpResponse req(String method, InputStream fobj, int comp, boolean hkey, JSONObject registerData, Connection.CancelCallback cancelCallback) {
    File tmpFileBuffer = null;
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        HashMap<String, Object> vars = new HashMap<String, Object>();
        // compression flag and session key as post vars
        vars.put("c", comp != 0 ? 1 : 0);
        if (hkey) {
            vars.put("k", mHKey);
            vars.put("s", mSKey);
        }
        for (String key : vars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key, vars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp", new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write("Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Collection.SYNC_URL;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password=" + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = url + "sync/" + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);
        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);
        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + AnkiDroidApp.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);
        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }
        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            return httpClient.execute(httpPost);
        } catch (SSLException e) {
            Log.e(AnkiDroidApp.TAG, "SSLException while building HttpClient", e);
            return null;
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Log.e(AnkiDroidApp.TAG, "BasicHttpSyncer.sync: IOException", e);
        return null;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) Scheme(org.apache.http.conn.scheme.Scheme) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) SSLException(javax.net.ssl.SSLException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) GZIPOutputStream(java.util.zip.GZIPOutputStream) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) JSONException(org.json.JSONException) ConnPerRouteBean(org.apache.http.conn.params.ConnPerRouteBean) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) JSONObject(org.json.JSONObject) EasySSLSocketFactory(org.apache.commons.httpclient.contrib.ssl.EasySSLSocketFactory)

Example 79 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project quickstarts by jboss-switchyard.

the class WorkServiceMain method main.

public static void main(String... args) throws Exception {
    Set<String> policies = new HashSet<String>();
    for (String arg : args) {
        arg = Strings.trimToNull(arg);
        if (arg != null) {
            if (arg.equals(CONFIDENTIALITY) || arg.equals(CLIENT_AUTHENTICATION) || arg.equals(HELP)) {
                policies.add(arg);
            } else {
                LOGGER.error(MAVEN_USAGE);
                throw new Exception(MAVEN_USAGE);
            }
        }
    }
    if (policies.contains(HELP)) {
        LOGGER.info(MAVEN_USAGE);
    } else {
        final String scheme;
        final int port;
        if (policies.contains(CONFIDENTIALITY)) {
            scheme = "https";
            port = getPort(8443);
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, null, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            Scheme https = new Scheme(scheme, port, sf);
            SchemeRegistry sr = new SchemeRegistry();
            sr.register(https);
        } else {
            scheme = "http";
            port = getPort(8080);
        }
        String username = policies.contains(CLIENT_AUTHENTICATION) ? "kermit" : "misspiggy";
        invokeWorkService(scheme, port, getContext(), username);
    }
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) HashSet(java.util.HashSet)

Example 80 with SchemeRegistry

use of org.apache.http.conn.scheme.SchemeRegistry in project cloudstack by apache.

the class NetScalerControlCenterResource method getHttpClient.

public static HttpClient getHttpClient() {
    HttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_PORT, sf));
        ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (KeyStoreException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    }
    return httpClient;
}
Also used : TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyManagementException(java.security.KeyManagementException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicClientConnectionManager(org.apache.http.impl.conn.BasicClientConnectionManager) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory)

Aggregations

SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)91 Scheme (org.apache.http.conn.scheme.Scheme)88 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)58 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)50 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)48 BasicHttpParams (org.apache.http.params.BasicHttpParams)35 HttpParams (org.apache.http.params.HttpParams)33 ThreadSafeClientConnManager (org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)30 SSLContext (javax.net.ssl.SSLContext)24 IOException (java.io.IOException)22 KeyManagementException (java.security.KeyManagementException)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18 CertificateException (java.security.cert.CertificateException)15 HttpClient (org.apache.http.client.HttpClient)12 BasicClientConnectionManager (org.apache.http.impl.conn.BasicClientConnectionManager)12 PoolingClientConnectionManager (org.apache.http.impl.conn.PoolingClientConnectionManager)12 KeyStoreException (java.security.KeyStoreException)11 UnrecoverableKeyException (java.security.UnrecoverableKeyException)10 X509Certificate (java.security.cert.X509Certificate)10 X509TrustManager (javax.net.ssl.X509TrustManager)9