Search in sources :

Example 51 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 52 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project baker-android by bakerframework.

the class CheckInternetTask method hasInternetConnection.

public boolean hasInternetConnection() {
    boolean result;
    try {
        final int timeout = this.context.getResources().getInteger(R.integer.check_internet_timeout);
        final String host = this.context.getString(R.string.check_internet_with_host);
        Log.d(this.getClass().toString(), "TESTING INTERNET CONNECTION WITH HOST " + host + " AND TIMEOUT " + timeout);
        //result = InetAddress.getByName(host).isReachable(timeout);
        HttpGet httpGet = new HttpGet(host);
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        // The default value is zero, that means the timeout is not used.
        //int timeoutConnection = 3000;
        //HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setSoTimeout(httpParameters, timeout);
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        Log.d(this.getClass().toString(), "THE TESTING INTERNET CONNECTION STATUS CODE WAS " + statusCode);
        if (statusCode == HttpStatus.SC_OK) {
            result = true;
        } else {
            result = false;
        }
    } catch (Exception ioe) {
        Log.e(this.getClass().toString(), ioe.getMessage());
        result = false;
    }
    return result;
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) BasicHttpParams(org.apache.http.params.BasicHttpParams) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 53 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project baker-android by bakerframework.

the class AndroidHttpClient method newInstance.

/**
     * Create a new HttpClient with reasonable defaults (which you can update).
     *
     * @param userAgent to report in your HTTP requests
     * @param context to use for caching SSL sessions (may be null for no caching)
     * @return AndroidHttpClient for you to use for all your requests.
     */
public static AndroidHttpClient newInstance(String userAgent, Context context) {
    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);
    HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
    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);
    Object sessionCache = null;
    // Use a session cache for SSL sockets -- Froyo only
    if (null != context && null != sSslSessionCacheClass) {
        Constructor<?> ct;
        try {
            ct = sSslSessionCacheClass.getConstructor(Context.class);
            sessionCache = ct.newInstance(context);
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    // 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));
    SocketFactory sslCertificateSocketFactory = null;
    if (null != sessionCache) {
        Method getHttpSocketFactoryMethod;
        try {
            getHttpSocketFactoryMethod = SSLCertificateSocketFactory.class.getDeclaredMethod("getHttpSocketFactory", Integer.TYPE, sSslSessionCacheClass);
            sslCertificateSocketFactory = (SocketFactory) getHttpSocketFactoryMethod.invoke(null, SOCKET_OPERATION_TIMEOUT, sessionCache);
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if (null == sslCertificateSocketFactory) {
        sslCertificateSocketFactory = SSLSocketFactory.getSocketFactory();
    }
    schemeRegistry.register(new Scheme("https", sslCertificateSocketFactory, 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
}
Also used : Context(android.content.Context) ClientContext(org.apache.http.client.protocol.ClientContext) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) Scheme(org.apache.http.conn.scheme.Scheme) PlainSocketFactory(org.apache.http.conn.scheme.PlainSocketFactory) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) SSLCertificateSocketFactory(android.net.SSLCertificateSocketFactory) SocketFactory(org.apache.http.conn.scheme.SocketFactory) Method(java.lang.reflect.Method) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) InvocationTargetException(java.lang.reflect.InvocationTargetException) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) SSLCertificateSocketFactory(android.net.SSLCertificateSocketFactory) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Example 54 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project h2o-2 by h2oai.

the class GoogleAnalyticsThreadFactory method createHttpClient.

protected HttpClient createHttpClient(GoogleAnalyticsConfig config) {
    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager();
    connManager.setDefaultMaxPerRoute(getDefaultMaxPerRoute(config));
    BasicHttpParams params = new BasicHttpParams();
    if (isNotEmpty(config.getUserAgent())) {
        params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgent());
    }
    if (isNotEmpty(config.getProxyHost())) {
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(config.getProxyHost(), config.getProxyPort()));
    }
    DefaultHttpClient client = new DefaultHttpClient(connManager, params);
    if (isNotEmpty(config.getProxyUserName())) {
        BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()), new UsernamePasswordCredentials(config.getProxyUserName(), config.getProxyPassword()));
        client.setCredentialsProvider(credentialsProvider);
    }
    return client;
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) BasicHttpParams(org.apache.http.params.BasicHttpParams) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 55 with BasicHttpParams

use of org.apache.http.params.BasicHttpParams in project Notes by lguipeng.

the class TEvernoteHttpClient method getHTTPClient.

@Deprecated
private DefaultHttpClient getHTTPClient() {
    try {
        if (mConnectionManager != null) {
            mConnectionManager.closeExpiredConnections();
            mConnectionManager.closeIdleConnections(1, TimeUnit.SECONDS);
        } else {
            BasicHttpParams params = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params, 10000);
            HttpConnectionParams.setSoTimeout(params, 20000);
            ConnManagerParams.setMaxTotalConnections(params, ConnManagerParams.DEFAULT_MAX_TOTAL_CONNECTIONS);
            ConnManagerParams.setTimeout(params, 10000);
            // Giving 18 connections to Evernote
            ConnPerRouteBean connPerRoute = new ConnPerRouteBean(18);
            ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
            mConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
            DefaultHttpClient httpClient = new DefaultHttpClient(mConnectionManager, params);
            httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {

                @Override
                public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                    // 2 minutes in millis
                    return 2 * 60 * 1000;
                }
            });
            httpClient.setReuseStrategy(new ConnectionReuseStrategy() {

                @Override
                public boolean keepAlive(HttpResponse response, HttpContext context) {
                    return true;
                }
            });
            mHttpClient = httpClient;
        }
    } catch (Exception ex) {
        return null;
    }
    return mHttpClient;
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) ConnectionKeepAliveStrategy(org.apache.http.conn.ConnectionKeepAliveStrategy) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) BasicHttpParams(org.apache.http.params.BasicHttpParams) ConnPerRouteBean(org.apache.http.conn.params.ConnPerRouteBean) ConnectionReuseStrategy(org.apache.http.ConnectionReuseStrategy) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) IOException(java.io.IOException) TTransportException(com.evernote.thrift.transport.TTransportException)

Aggregations

BasicHttpParams (org.apache.http.params.BasicHttpParams)82 HttpParams (org.apache.http.params.HttpParams)62 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)47 IOException (java.io.IOException)33 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)31 Scheme (org.apache.http.conn.scheme.Scheme)30 ThreadSafeClientConnManager (org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)29 HttpResponse (org.apache.http.HttpResponse)27 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)24 ClientProtocolException (org.apache.http.client.ClientProtocolException)15 HttpClient (org.apache.http.client.HttpClient)12 HttpGet (org.apache.http.client.methods.HttpGet)12 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)12 Socket (java.net.Socket)11 HttpPost (org.apache.http.client.methods.HttpPost)10 ConnectException (java.net.ConnectException)8 KeyManagementException (java.security.KeyManagementException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 SSLContext (javax.net.ssl.SSLContext)8 StringEntity (org.apache.http.entity.StringEntity)8