Search in sources :

Example 91 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project keycloak by keycloak.

the class HttpClientBuilder method build.

public HttpClient build() {
    X509HostnameVerifier verifier = null;
    if (this.verifier != null)
        verifier = new VerifierWrapper(this.verifier);
    else {
        switch(policy) {
            case ANY:
                verifier = new AllowAllHostnameVerifier();
                break;
            case WILDCARD:
                verifier = new BrowserCompatHostnameVerifier();
                break;
            case STRICT:
                verifier = new StrictHostnameVerifier();
                break;
        }
    }
    try {
        SSLSocketFactory sslsf = null;
        SSLContext theContext = sslContext;
        if (disableTrustManager) {
            theContext = SSLContext.getInstance("SSL");
            theContext.init(null, new TrustManager[] { new PassthroughTrustManager() }, new SecureRandom());
            verifier = new AllowAllHostnameVerifier();
            sslsf = new SniSSLSocketFactory(theContext, verifier);
        } else if (theContext != null) {
            sslsf = new SniSSLSocketFactory(theContext, verifier);
        } else if (clientKeyStore != null || truststore != null) {
            sslsf = new SniSSLSocketFactory(SSLSocketFactory.TLS, clientKeyStore, clientPrivateKeyPassword, truststore, null, verifier);
        } else {
            final SSLContext tlsContext = SSLContext.getInstance(SSLSocketFactory.TLS);
            tlsContext.init(null, null, null);
            sslsf = new SniSSLSocketFactory(tlsContext, verifier);
        }
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        registry.register(httpsScheme);
        ClientConnectionManager cm = null;
        if (connectionPoolSize > 0) {
            ThreadSafeClientConnManager tcm = new ThreadSafeClientConnManager(registry, connectionTTL, connectionTTLUnit);
            tcm.setMaxTotal(connectionPoolSize);
            if (maxPooledPerRoute == 0)
                maxPooledPerRoute = connectionPoolSize;
            tcm.setDefaultMaxPerRoute(maxPooledPerRoute);
            cm = tcm;
        } else {
            cm = new SingleClientConnManager(registry);
        }
        BasicHttpParams params = new BasicHttpParams();
        params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        if (proxyHost != null) {
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }
        if (socketTimeout > -1) {
            HttpConnectionParams.setSoTimeout(params, (int) socketTimeoutUnits.toMillis(socketTimeout));
        }
        if (establishConnectionTimeout > -1) {
            HttpConnectionParams.setConnectionTimeout(params, (int) establishConnectionTimeoutUnits.toMillis(establishConnectionTimeout));
        }
        DefaultHttpClient client = new DefaultHttpClient(cm, params);
        if (disableCookieCache) {
            client.setCookieStore(new CookieStore() {

                @Override
                public void addCookie(Cookie cookie) {
                // To change body of implemented methods use File | Settings | File Templates.
                }

                @Override
                public List<Cookie> getCookies() {
                    return Collections.emptyList();
                }

                @Override
                public boolean clearExpired(Date date) {
                    // To change body of implemented methods use File | Settings | File Templates.
                    return false;
                }

                @Override
                public void clear() {
                // To change body of implemented methods use File | Settings | File Templates.
                }
            });
        }
        return client;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : Cookie(org.apache.http.cookie.Cookie) Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) Date(java.util.Date) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) CookieStore(org.apache.http.client.CookieStore) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier) SingleClientConnManager(org.apache.http.impl.conn.SingleClientConnManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BrowserCompatHostnameVerifier(org.apache.http.conn.ssl.BrowserCompatHostnameVerifier) List(java.util.List) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Example 92 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project keycloak by keycloak.

the class HttpClientBuilder method build.

public HttpClient build() {
    X509HostnameVerifier verifier = null;
    if (this.verifier != null)
        verifier = new VerifierWrapper(this.verifier);
    else {
        switch(policy) {
            case ANY:
                verifier = new AllowAllHostnameVerifier();
                break;
            case WILDCARD:
                verifier = new BrowserCompatHostnameVerifier();
                break;
            case STRICT:
                verifier = new StrictHostnameVerifier();
                break;
        }
    }
    try {
        SSLSocketFactory sslsf = null;
        SSLContext theContext = sslContext;
        if (disableTrustManager) {
            theContext = SSLContext.getInstance("SSL");
            theContext.init(null, new TrustManager[] { new PassthroughTrustManager() }, new SecureRandom());
            verifier = new AllowAllHostnameVerifier();
            sslsf = new SniSSLSocketFactory(theContext, verifier);
        } else if (theContext != null) {
            sslsf = new SniSSLSocketFactory(theContext, verifier);
        } else if (clientKeyStore != null || truststore != null) {
            sslsf = new SniSSLSocketFactory(SSLSocketFactory.TLS, clientKeyStore, clientPrivateKeyPassword, truststore, null, verifier);
        } else {
            final SSLContext tlsContext = SSLContext.getInstance(SSLSocketFactory.TLS);
            tlsContext.init(null, null, null);
            sslsf = new SniSSLSocketFactory(tlsContext, verifier);
        }
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        registry.register(httpsScheme);
        ClientConnectionManager cm = null;
        if (connectionPoolSize > 0) {
            ThreadSafeClientConnManager tcm = new ThreadSafeClientConnManager(registry, connectionTTL, connectionTTLUnit);
            tcm.setMaxTotal(connectionPoolSize);
            if (maxPooledPerRoute == 0)
                maxPooledPerRoute = connectionPoolSize;
            tcm.setDefaultMaxPerRoute(maxPooledPerRoute);
            cm = tcm;
        } else {
            cm = new SingleClientConnManager(registry);
        }
        BasicHttpParams params = new BasicHttpParams();
        params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        if (proxyHost != null) {
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }
        if (socketTimeout > -1) {
            HttpConnectionParams.setSoTimeout(params, (int) socketTimeoutUnits.toMillis(socketTimeout));
        }
        if (establishConnectionTimeout > -1) {
            HttpConnectionParams.setConnectionTimeout(params, (int) establishConnectionTimeoutUnits.toMillis(establishConnectionTimeout));
        }
        DefaultHttpClient client = new DefaultHttpClient(cm, params);
        if (disableCookieCache) {
            client.setCookieStore(new CookieStore() {

                @Override
                public void addCookie(Cookie cookie) {
                // To change body of implemented methods use File | Settings | File Templates.
                }

                @Override
                public List<Cookie> getCookies() {
                    return Collections.emptyList();
                }

                @Override
                public boolean clearExpired(Date date) {
                    // To change body of implemented methods use File | Settings | File Templates.
                    return false;
                }

                @Override
                public void clear() {
                // To change body of implemented methods use File | Settings | File Templates.
                }
            });
        }
        return client;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : Cookie(org.apache.http.cookie.Cookie) Scheme(org.apache.http.conn.scheme.Scheme) AllowAllHostnameVerifier(org.apache.http.conn.ssl.AllowAllHostnameVerifier) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) Date(java.util.Date) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) CookieStore(org.apache.http.client.CookieStore) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) StrictHostnameVerifier(org.apache.http.conn.ssl.StrictHostnameVerifier) SingleClientConnManager(org.apache.http.impl.conn.SingleClientConnManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BrowserCompatHostnameVerifier(org.apache.http.conn.ssl.BrowserCompatHostnameVerifier) List(java.util.List) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Example 93 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project newsrob by marianokamp.

the class CountingInputStream method newInstance.

public static NewsRobHttpClient newInstance(boolean followRedirects, Context ctx) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setConnectionTimeout(params, 45 * 1000);
    HttpConnectionParams.setSoTimeout(params, 45 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    // HttpConnectionParams.setTcpNoDelay(params, true);
    // 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);
    HttpClientParams.setRedirecting(params, followRedirects);
    if (followRedirects)
        params.setIntParameter(ClientPNames.MAX_REDIRECTS, 10);
    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, USER_AGENT);
    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 NewsRobHttpClient(manager, params, ctx);
}
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 94 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project Java-readability by basis-technology-corp.

the class HttpPageReader method readPage.

/**
 * {@inheritDoc}
 */
@Override
public String readPage(String url) throws PageReadException {
    LOG.info("Reading " + url);
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 10000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpContext localContext = new BasicHttpContext();
    HttpGet get = new HttpGet(url);
    InputStream response = null;
    HttpResponse httpResponse = null;
    try {
        try {
            httpResponse = httpclient.execute(get, localContext);
            int resp = httpResponse.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK != resp) {
                LOG.error("Download failed of " + url + " status " + resp + " " + httpResponse.getStatusLine().getReasonPhrase());
                return null;
            }
            String respCharset = EntityUtils.getContentCharSet(httpResponse.getEntity());
            return readContent(httpResponse.getEntity().getContent(), respCharset);
        } finally {
            if (response != null) {
                response.close();
            }
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().consumeContent();
            }
        }
    } catch (IOException e) {
        LOG.error("Download failed of " + url, e);
        throw new PageReadException("Failed to read " + url, e);
    }
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) BasicHttpParams(org.apache.http.params.BasicHttpParams) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 95 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project Talon-for-Twitter by klinker24.

the class TwitterMultipleImageHelper method uploadPics.

public boolean uploadPics(File[] pics, String text, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    final String ids_string = getMediaIds(pics, twitter);
    if (ids_string == null) {
        return false;
    }
    try {
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();
        // generate authorization header
        String get_or_post = "POST";
        String oauth_signature_method = "HMAC-SHA1";
        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        // any relatively random alphanumeric string will work here
        String oauth_nonce = uuid_string;
        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        // get current time in milliseconds
        long ts = tempcal.getTimeInMillis();
        // then divide by 1000 to get seconds
        String oauth_timestamp = (new Long(ts / 1000)).toString();
        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
        System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);
        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/update.json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));
        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors
        new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors
        new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });
        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
        try {
            try {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, null, null);
                SSLSocketFactory ssf = sslcontext.getSocketFactory();
                Socket socket = ssf.createSocket();
                socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                conn.bind(socket, params);
                BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path);
                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("media_ids", new StringBody(ids_string));
                reqEntity.addPart("status", new StringBody(text));
                reqEntity.addPart("trim_user", new StringBody("1"));
                request2.setEntity(reqEntity);
                request2.setParams(params);
                request2.addHeader("Authorization", authorization_header_string);
                httpexecutor.preProcess(request2, httpproc, context);
                HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                response2.setParams(params);
                httpexecutor.postProcess(response2, httpproc, context);
                String responseBody = EntityUtils.toString(response2.getEntity());
                System.out.println("response=" + responseBody);
                // error checking here. Otherwise, status should be updated.
                jsonresponse = new JSONObject(responseBody);
                conn.close();
            } catch (HttpException he) {
                System.out.println(he.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage());
            } catch (NoSuchAlgorithmException nsae) {
                System.out.println(nsae.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage());
            } catch (KeyManagementException kme) {
                System.out.println(kme.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage());
            } finally {
                conn.close();
            }
        } catch (JSONException jsone) {
            jsone.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    } catch (Exception e) {
    }
    return true;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) AccessToken(twitter4j.auth.AccessToken) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) Calendar(java.util.Calendar) JSONException(org.json.JSONException) DefaultHttpClientConnection(org.apache.http.impl.DefaultHttpClientConnection) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) JSONException(org.json.JSONException) GeneralSecurityException(java.security.GeneralSecurityException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TwitterException(twitter4j.TwitterException) IOException(java.io.IOException) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) HttpParams(org.apache.http.params.HttpParams) JSONObject(org.json.JSONObject) StringBody(org.apache.http.entity.mime.content.StringBody) Socket(java.net.Socket)

Aggregations

BasicHttpParams (org.apache.http.params.BasicHttpParams)120 HttpParams (org.apache.http.params.HttpParams)75 IOException (java.io.IOException)55 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)51 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)34 Scheme (org.apache.http.conn.scheme.Scheme)33 HttpResponse (org.apache.http.HttpResponse)32 ThreadSafeClientConnManager (org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)32 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)27 Test (org.junit.Test)27 URI (java.net.URI)24 ArrayList (java.util.ArrayList)20 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)19 HttpServletRequest (javax.servlet.http.HttpServletRequest)18 HttpServletResponse (javax.servlet.http.HttpServletResponse)18 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)18 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)17 FilterConfig (javax.servlet.FilterConfig)17 ServletContext (javax.servlet.ServletContext)17 HaDescriptor (org.apache.knox.gateway.ha.provider.HaDescriptor)17