Example usage for org.apache.http.conn.ssl SSLSocketFactory getSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLSocketFactory getSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLSocketFactory getSocketFactory.

Prototype

public static SSLSocketFactory getSocketFactory() throws SSLInitializationException 

Source Link

Document

Obtains default SSL socket factory with an SSL context based on the standard JSSE trust material (cacerts file in the security properties directory).

Usage

From source file:cn.edu.szjm.support.http.IgnitedHttp.java

protected void setupHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, DEFAULT_WAIT_FOR_CONNECTION_TIMEOUT);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, DEFAULT_HTTP_USER_AGENT);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (IgnitedDiagnostics.ANDROID_API_LEVEL >= 7) {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    } else {// ww w .  j a  v a  2  s  .c o  m
        // used to work around a bug in Android 1.6:
        // http://code.google.com/p/android/issues/detail?id=1946
        // TODO: is there a less rigorous workaround for this?
        schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    }

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, httpParams);
}

From source file:org.frameworkset.spi.remote.http.Client.java

protected static ClientConnectionManager createClientConnectionManager()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException,
        IOException, KeyManagementException, UnrecoverableKeyException {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    ProMap ssls = ApplicationContext.getApplicationContext().getMapProperty("rpc.protocol.http.ssl.client");
    ssls = null;//  w  w w. j a  va  2 s . c  om
    if (ssls == null) {
        registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        //            throw new Exception(
        //                  "?ssl? rpc.protocol.http.ssl.server ?org/frameworkset/spi/manager-rpc-http.xml??");
    } else {
        String trustStore_ = ssls.getString("trustStore");
        String trustStorePassword = ssls.getString("trustStorePassword");
        KeyStore trustStore = SSLHelper.getKeyStore(trustStore_, trustStorePassword);

        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
        registry.register(new Scheme("https", socketFactory, 443));
    }

    ClientConnectionManager connManager = null;

    ClientConnectionManagerFactory factory = null;

    connManager = new ThreadSafeClientConnManager(params, registry);

    return connManager;
}

From source file:com.mnxfst.testing.client.TSClientPlanResultCollectCallable.java

public TSClientPlanResultCollectCallable(String hostname, int port, String uri) {
    this.httpHost = new HttpHost(hostname, port);
    this.getMethod = new HttpGet(uri.toString());

    // TODO setting?
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    ThreadSafeClientConnManager threadSafeClientConnectionManager = new ThreadSafeClientConnManager(
            schemeRegistry);//from   w ww .  j  a v a 2 s.  c  om
    threadSafeClientConnectionManager.setMaxTotal(20);
    threadSafeClientConnectionManager.setDefaultMaxPerRoute(20);
    this.httpClient = new DefaultHttpClient(threadSafeClientConnectionManager);
}

From source file:com.autonomousturk.crawler.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

    params.setBooleanParameter("http.protocol.handle-redirects", false);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    if (config.isIncludeHttpsPages()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }/*ww  w  . java 2s  .  c  o m*/

    connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);

    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != null) {
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }

    });

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();

}

From source file:org.sbs.goodcrawler.fetcher.PageFetcher.java

public PageFetcher(FetchConfig config) {
    super(config);
    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getAgent());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeoutMilliseconds());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

    params.setBooleanParameter("http.protocol.handle-redirects", false);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    if (config.isHttps()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }/* w w  w  .  ja va  2s .  c  o  m*/

    connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);

    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != null) {
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }

    });

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();

}

From source file:com.photowall.oauth.util.BaseHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 *
 * @param userAgent to report in your HTTP requests.
 * @param sessionCache persistent session cache
 * @return AndroidHttpClient for you to use for all your requests.
 *///  ww  w .j  a v a2s  .co m
public static BaseHttpClient newInstance(Context mContext, 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);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new BaseHttpClient(mContext, manager, params);
}

From source file:com.mnxfst.testing.client.TSClientPlanExecCallable.java

public TSClientPlanExecCallable(String hostname, int port, String uri, byte[] testplan) {
    this.httpHost = new HttpHost(hostname, port);
    //      this.getMethod = new HttpGet(uri.toString());
    this.postMethod = new HttpPost(uri.toString());
    try {//  w w w . j a  va 2  s  .  c om
        String convertedTestplan = new String(testplan, "UTF-8");
        postMethod.setEntity(new StringEntity(
                TSClient.REQUEST_PARAMETER_TESTPLAN + "=" + URLEncoder.encode(convertedTestplan, "UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Unsupported encoding exception. Error: " + e.getMessage());
    }

    // TODO setting?
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    ThreadSafeClientConnManager threadSafeClientConnectionManager = new ThreadSafeClientConnManager(
            schemeRegistry);
    threadSafeClientConnectionManager.setMaxTotal(20);
    threadSafeClientConnectionManager.setDefaultMaxPerRoute(20);
    this.httpClient = new DefaultHttpClient(threadSafeClientConnectionManager);

}

From source file:com.mockey.ClientExecuteProxy.java

/**
 * //from   w ww.  j  a v  a  2 s. c o  m
 * @param twistInfo
 * @param proxyServer
 * @param realServiceUrl
 * @param httpMethod
 * @param request
 * @return
 * @throws ClientExecuteProxyException
 */
public ResponseFromService execute(TwistInfo twistInfo, ProxyServerModel proxyServer, Url realServiceUrl,
        boolean allowRedirectFollow, RequestFromClient request) throws ClientExecuteProxyException {
    log.info("Request: " + String.valueOf(realServiceUrl));

    // general setup
    SchemeRegistry supportedSchemes = new SchemeRegistry();

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.ISO_8859_1);
    HttpProtocolParams.setUseExpectContinue(params, false);

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(supportedSchemes);
    DefaultHttpClient httpclient = new DefaultHttpClient(ccm, params);

    if (!allowRedirectFollow) {
        // Do NOT allow for 302 REDIRECT
        httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
            public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
                boolean isRedirect = false;
                try {
                    isRedirect = super.isRedirected(request, response, context);
                } catch (ProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (!isRedirect) {
                    int responseCode = response.getStatusLine().getStatusCode();
                    if (responseCode == 301 || responseCode == 302) {
                        return true;
                    }
                }
                return isRedirect;
            }
        });
    } else {
        // Yes, allow for 302 REDIRECT
        // Nothing needed here.
    }

    // Prevent CACHE, 304 not modified
    //      httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
    //         public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    //            
    //            request.setHeader("If-modified-Since", "Fri, 13 May 2006 23:54:18 GMT");
    //
    //         }
    //      });

    CookieStore cookieStore = httpclient.getCookieStore();
    for (Cookie httpClientCookie : request.getHttpClientCookies()) {
        // HACK:
        // httpClientCookie.getValue();
        cookieStore.addCookie(httpClientCookie);
    }
    // httpclient.setCookieStore(cookieStore);

    if (ClientExecuteProxy.cookieStore == null) {
        ClientExecuteProxy.cookieStore = httpclient.getCookieStore();

    } else {
        httpclient.setCookieStore(ClientExecuteProxy.cookieStore);
    }

    StringBuffer requestCookieInfo = new StringBuffer();
    // Show what cookies are in the store .
    for (Cookie cookie : ClientExecuteProxy.cookieStore.getCookies()) {
        log.debug("Cookie in the cookie STORE: " + cookie.toString());
        requestCookieInfo.append(cookie.toString() + "\n\n\n");

    }

    if (proxyServer.isProxyEnabled()) {
        // make sure to use a proxy that supports CONNECT
        httpclient.getCredentialsProvider().setCredentials(proxyServer.getAuthScope(),
                proxyServer.getCredentials());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyServer.getHttpHost());
    }

    // TWISTING
    Url originalRequestUrlBeforeTwisting = null;
    if (twistInfo != null) {
        String fullurl = realServiceUrl.getFullUrl();
        String twistedUrl = twistInfo.getTwistedValue(fullurl);
        if (twistedUrl != null) {
            originalRequestUrlBeforeTwisting = realServiceUrl;
            realServiceUrl = new Url(twistedUrl);
        }
    }

    ResponseFromService responseMessage = null;
    try {
        HttpHost htttphost = new HttpHost(realServiceUrl.getHost(), realServiceUrl.getPort(),
                realServiceUrl.getScheme());

        HttpResponse response = httpclient.execute(htttphost, request.postToRealServer(realServiceUrl));
        if (response.getStatusLine().getStatusCode() == 302) {
            log.debug("FYI: 302 redirect occuring from " + realServiceUrl.getFullUrl());
        }
        responseMessage = new ResponseFromService(response);
        responseMessage.setOriginalRequestUrlBeforeTwisting(originalRequestUrlBeforeTwisting);
        responseMessage.setRequestUrl(realServiceUrl);
    } catch (Exception e) {
        log.error(e);
        throw new ClientExecuteProxyException("Unable to retrieve a response. ", realServiceUrl, e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    // Parse out the response information we're looking for
    // StringBuffer responseCookieInfo = new StringBuffer();
    // // Show what cookies are in the store .
    // for (Cookie cookie : ClientExecuteProxy.cookieStore.getCookies()) {
    // log.info("Cookie in the cookie STORE: " + cookie.toString());
    // responseCookieInfo.append(cookie.toString() + "\n\n\n");
    //
    // }
    // responseMessage.setRequestCookies(requestCookieInfo.toString());
    // responseMessage.setResponseCookies(responseCookieInfo.toString());
    return responseMessage;
}

From source file:com.nookdevs.library.Smashwords.java

private boolean authenticate() {
    String url = AUTH_URL;
    try {/*from  w  w  w  . ja  va  2s.  co m*/
        nookLib.waitForNetwork(lock);
        SSLSocketFactory factory = SSLSocketFactory.getSocketFactory();
        X509HostnameVerifier orgVerifier = factory.getHostnameVerifier();
        factory.setHostnameVerifier(new AllowAllHostnameVerifier());
        HttpPost request = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", m_User));
        nvps.add(new BasicNameValuePair("password", m_Pass));
        request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        HttpResponse response = httpClient.execute(request);
        parseBookShelf(response.getEntity().getContent());
        factory.setHostnameVerifier(orgVerifier);
        lock.release();
        return true;
    } catch (Exception ex) {
        Log.e("Smashwords", "exception during authentication", ex);
        return false;
    }
}