Example usage for org.apache.http.params HttpProtocolParams setUserAgent

List of usage examples for org.apache.http.params HttpProtocolParams setUserAgent

Introduction

In this page you can find the example usage for org.apache.http.params HttpProtocolParams setUserAgent.

Prototype

public static void setUserAgent(HttpParams httpParams, String str) 

Source Link

Usage

From source file:org.accesointeligente.server.robots.SGS110.java

public SGS110() {
    client = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(client.getParams(),
            "Mozilla/5.0 (X11; U; Linux x86_64; es-CL; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.10 (maverick) Firefox/3.6.12");
    HttpProtocolParams.setVersion(client.getParams(), HttpVersion.HTTP_1_0);
    cleaner = new HtmlCleaner();
}

From source file:org.silvertunnel_ng.demo.download_tool.ApacheHttpComponentsClient.java

/**
 * Initialize HttpComponents Client// ww  w .  ja v  a2  s .c o m
 * 
 * @param lowerNetLayer    TCP/IP compatible layer;
 *                         layer for SSL/TLS/https connections
 *                         will be created inside this class
 *                         and may not be passed as argument here 
 */
public ApacheHttpComponentsClient(NetLayer lowerNetLayer) {
    // register the "http" protocol scheme, it is required
    // by the default operator to look up socket factories.
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    final int DEFAULT_PORT_HTTP = 80;
    schemeRegistry.register(new Scheme("http", new NetlibSocketFactory(lowerNetLayer), DEFAULT_PORT_HTTP));

    /* TODO - DOES CURRENTLY NOT WORK: register the "https" protocol scheme
    final int DEFAULT_PORT_HTTPS = 443;
    NetLayer httpsLowerNetLayer = new TLSNetLayer(lowerNetLayer);  
    schemeRegistry.register(new Scheme("https", new NetlibSocketFactory(httpsLowerNetLayer), DEFAULT_PORT_HTTPS));
    */

    // set http(s) client parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    if (USER_AGENT != null) {
        HttpProtocolParams.setUserAgent(params, USER_AGENT);
    }

    // create http(s) client
    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, schemeRegistry);
    httpClient = new DefaultHttpClient(ccm, params);

    log.info("HttpComponents Client/httpClient initialized=" + httpClient.toString());
}

From source file:jetbrains.buildServer.commitPublisher.github.api.impl.HttpClientWrapperImpl.java

public HttpClientWrapperImpl()
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    final String serverVersion = ServerVersionHolder.getVersion().getDisplayVersion();

    final HttpParams ps = new BasicHttpParams();

    DefaultHttpClient.setDefaultHttpParams(ps);
    final int timeout = TeamCityProperties.getInteger("teamcity.github.http.timeout", 300 * 1000);
    HttpConnectionParams.setConnectionTimeout(ps, timeout);
    HttpConnectionParams.setSoTimeout(ps, timeout);
    HttpProtocolParams.setUserAgent(ps, "JetBrains TeamCity " + serverVersion);

    final SchemeRegistry schemaRegistry = SchemeRegistryFactory.createDefault();
    final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return !TeamCityProperties.getBoolean("teamcity.github.verify.ssl.certificate");
        }//  w w  w .  j a  v a 2 s.  c  om
    }) {
        @Override
        public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host,
                InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context)
                throws IOException {
            if (socket instanceof SSLSocket) {
                try {
                    PropertyUtils.setProperty(socket, "host", host.getHostName());
                } catch (Exception ex) {
                    LOG.warn(String.format(
                            "A host name is not passed to SSL connection for the purpose of supporting SNI due to the following exception: %s",
                            ex.toString()));
                }
            }
            return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
        }
    };
    schemaRegistry.register(new Scheme("https", 443, sslSocketFactory));

    final DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(schemaRegistry),
            ps);

    setupProxy(httpclient);

    httpclient.setRoutePlanner(new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()));
    httpclient.addRequestInterceptor(new RequestAcceptEncoding());
    httpclient.addResponseInterceptor(new ResponseContentEncoding());
    httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    myClient = httpclient;
}

From source file:com.prey.net.PreyRestHttpClient.java

private PreyRestHttpClient(Context ctx) {
    this.ctx = ctx;
    httpclient = new PreyDefaultHttpClient((DefaultHttpClient) HttpUtils.getNewHttpClient());
    httpclientDefault = new PreyDefaultHttpClient((DefaultHttpClient) HttpUtils.getNewHttpClient());

    HttpParams params = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = 30000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 50000;
    HttpConnectionParams.setSoTimeout(params, timeoutSocket);

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF_8");
    HttpProtocolParams.setUseExpectContinue(params, false);
    HttpParams paramsDefault = params;//from  w  w w . jav  a  2 s  .  c  o m
    httpclientDefault.setParams(paramsDefault);
    HttpProtocolParams.setUserAgent(params, getUserAgent());
    httpclient.setParams(params);
}

From source file:ch.cyberduck.core.http.HttpSession.java

protected AbstractHttpClient http(final String hostname) {
    if (!clients.containsKey(hostname)) {
        final HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, getEncoding());
        HttpProtocolParams.setUserAgent(params, getUserAgent());

        AuthParams.setCredentialCharset(params, Preferences.instance().getProperty("http.credentials.charset"));

        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoTimeout(params, timeout());
        HttpConnectionParams.setConnectionTimeout(params, timeout());
        HttpConnectionParams.setSocketBufferSize(params,
                Preferences.instance().getInteger("http.socket.buffer"));
        HttpConnectionParams.setStaleCheckingEnabled(params, true);

        HttpClientParams.setRedirecting(params, true);
        HttpClientParams.setAuthenticating(params, true);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH);

        // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager
        HttpClientParams.setConnectionManagerTimeout(params,
                Preferences.instance().getLong("http.manager.timeout"));

        SchemeRegistry registry = new SchemeRegistry();
        // Always register HTTP for possible use with proxy
        registry.register(new Scheme(ch.cyberduck.core.Scheme.http.toString(), host.getPort(),
                PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme(ch.cyberduck.core.Scheme.https.toString(), host.getPort(),
                new SSLSocketFactory(
                        new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(),
                        new X509HostnameVerifier() {
                            @Override
                            public void verify(String host, SSLSocket ssl) throws IOException {
                                log.warn("Hostname verification disabled for:" + host);
                            }//  ww  w.j  ava2 s. com

                            @Override
                            public void verify(String host, X509Certificate cert) throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public void verify(String host, String[] cns, String[] subjectAlts)
                                    throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public boolean verify(String s, javax.net.ssl.SSLSession sslSession) {
                                log.warn("Hostname verification disabled for:" + s);
                                return true;
                            }
                        })));
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.get();
            if (ch.cyberduck.core.Scheme.https.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPSProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)));
                }
            }
            if (ch.cyberduck.core.Scheme.http.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host)));
                }
            }
        }
        PoolingClientConnectionManager manager = new PoolingClientConnectionManager(registry);
        manager.setMaxTotal(Preferences.instance().getInteger("http.connections.total"));
        manager.setDefaultMaxPerRoute(Preferences.instance().getInteger("http.connections.route"));
        AbstractHttpClient http = new DefaultHttpClient(manager, params);
        this.configure(http);
        clients.put(hostname, http);
    }
    return clients.get(hostname);
}

From source file:me.xiaopan.android.gohttp.HttpClientManager.java

public HttpClientManager(SchemeRegistry schemeRegistry) {
    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setTcpNoDelay(httpParams, true); //?TCP
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); //Http??
    HttpProtocolParams.setUserAgent(httpParams, DEFAULT_USER_AGENT); //?
    httpContext = new SyncBasicHttpContext(new BasicHttpContext()); //?Http
    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
    httpClient.addRequestInterceptor(new GzipProcessRequestInterceptor());
    httpClient.addRequestInterceptor(new AddRequestHeaderRequestInterceptor(getHeaderMap()));
    httpClient.addResponseInterceptor(new GzipProcessResponseInterceptor());
    httpClient// w w  w  .  ja  v a  2s  . c  o m
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
    clientHeaderMap = new HashMap<String, String>();
    setTimeout(DEFAULT_TIMEOUT);
    setMaxConnections(DEFAULT_MAX_CONNECTIONS);
    setSocketBufferSize(DEFAULT_SOCKET_BUFFER_SIZE);
}

From source file:org.thoughtcrime.securesms.mms.MmsCommunication.java

protected static HttpClient constructHttpClient(MmsConnectionParameters mmsConfig) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    HttpClientParams.setRedirecting(params, false);
    HttpProtocolParams.setUserAgent(params, "TextSecure/0.1");
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    if (mmsConfig.hasProxy()) {
        ConnRouteParams.setDefaultProxy(params, new HttpHost(mmsConfig.getProxy(), mmsConfig.getPort()));
    }//  w  w  w .  j  a v a  2s  . c  o m

    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);
    return new DefaultHttpClient(manager, params);
}

From source file:com.dfws.idea.ViewSourceActivity.java

protected String fileGetContents(String url) {

    String returnStr = "";

    HttpGet httpGet = new HttpGet(url);

    HttpParams httpParams = new BasicHttpParams();

    //  Socket ? Socket ?
    HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
    HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
    // ??? true//from  w w w . j ava  2 s  .  c  o m
    HttpClientParams.setRedirecting(httpParams, true);
    //  user agent
    String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";
    HttpProtocolParams.setUserAgent(httpParams, userAgent);

    HttpClient httpClient = new DefaultHttpClient(httpParams);

    try {
        HttpResponse response = httpClient.execute(httpGet);

        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == ClosePcActivity.OK_STATUS_CODE) {
            // ?
            returnStr = EntityUtils.toString(response.getEntity());
        } else {
            Toast.makeText(ViewSourceActivity.this, "???", Toast.LENGTH_SHORT).show();
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        String strResult = e.getMessage().toString();
        Log.i("test", strResult);
        e.printStackTrace();
    }
    return returnStr;
}

From source file:com.lonepulse.robozombie.executor.ConfigurationService.java

/**
 * <p>The <i>out-of-the-box</i> configuration for an instance of {@link HttpClient} which will be used for 
 * executing all endpoint requests. Below is a detailed description of all configured properties.</p> 
 * <br>/*from   w w  w .  j av  a2  s.c  om*/
 * <ul>
 * <li>
 * <p><b>HttpClient</b></p>
 * <br>
 * <p>It registers two {@link Scheme}s:</p>
 * <br>
 * <ol>
 *    <li><b>HTTP</b> on port <b>80</b> using sockets from {@link PlainSocketFactory#getSocketFactory}</li>
 *    <li><b>HTTPS</b> on port <b>443</b> using sockets from {@link SSLSocketFactory#getSocketFactory}</li>
 * </ol>
 * 
 * <p>It uses a {@link ThreadSafeClientConnManager} with the following parameters:</p>
 * <br>
 * <ol>
 *    <li><b>Redirecting:</b> enabled</li>
 *    <li><b>Connection Timeout:</b> 30 seconds</li>
 *    <li><b>Socket Timeout:</b> 30 seconds</li>
 *    <li><b>Socket Buffer Size:</b> 12000 bytes</li>
 *    <li><b>User-Agent:</b> via <code>System.getProperty("http.agent")</code></li>
 * </ol>
 * </li>
 * </ul>
 * @return the instance of {@link HttpClient} which will be used for request execution
 * <br><br>
 * @since 1.3.0
 */
@Override
public Configuration getDefault() {

    return new Configuration() {

        @Override
        public HttpClient httpClient() {

            try {

                HttpParams params = new BasicHttpParams();
                HttpClientParams.setRedirecting(params, true);
                HttpConnectionParams.setConnectionTimeout(params, 30 * 1000);
                HttpConnectionParams.setSoTimeout(params, 30 * 1000);
                HttpConnectionParams.setSocketBufferSize(params, 12000);
                HttpProtocolParams.setUserAgent(params, System.getProperty("http.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);

                return new DefaultHttpClient(manager, params);
            } catch (Exception e) {

                throw new ConfigurationFailedException(e);
            }
        }
    };
}