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:com.strato.hidrive.api.connection.httpgateway.HTTPGateway.java

public void setUserAgentString(String userAgentString) {
    HttpProtocolParams.setUserAgent(httpClient.getParams(), userAgentString);
}

From source file:matroskastudycoder.HttpControl.java

public void init(String aHost, String aPort) throws Exception {
    params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    httpexecutor = new HttpRequestExecutor();

    context = new BasicHttpContext(null);
    host = new HttpHost(aHost, Integer.parseInt(aPort));

    connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    //Clear the playlist
    sendGetRequest("/requests/status.xml?command=pl_empty");

    //Load the media
    String m = this.mediaPath;
    m = m.replaceAll("\\\\", "\\\\\\\\");

    sendGetRequest("/requests/status.xml?command=in_play&input=" + URLEncoder.encode(m, "UTF-8"));
    sendGetRequest("/requests/status.xml?command=pl_pause");
    initialized = true;//w w  w . jav a2 s . c om
}

From source file:com.github.diogochbittencourt.googleplaydownloader.downloader.impl.AndroidHttpClient.java

/**
 * 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.
 *///from  www.j  a  v  a2  s .c  o  m
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);

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

From source file:org.auraframework.integration.test.util.IntegrationTestCase.java

/**
 * Set the desired user agent to be used in HttpClient requests from this test
 *///from  w  ww  . ja  v a  2 s . com
protected void setHttpUserAgent(String userAgentString) throws Exception {
    HttpProtocolParams.setUserAgent(getHttpClient().getParams(), userAgentString);
}

From source file:com.example.wechatsample.library.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from  w  w  w.j ava 2  s.  c  om
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));
    ThreadSafeClientConnManager cm = null;
    try {
        //  https?
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // ??

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", sf, 443));
        schemeRegistry.register(new Scheme("https", sf, 8443));
        cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:net.sf.jsog.client.DefaultHttpClientImpl.java

/**
 * Sets the value of the User-Agent header, if any.
 *
 * @param userAgent the user agent string.
 *//*from w  w  w  . ja  va 2s.  c o m*/
public final synchronized void setUserAgent(String userAgent) {
    HttpProtocolParams.setUserAgent(params, userAgent);
}

From source file:lynxtools.async_download.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.// ww  w .  jav  a  2s  .  c  o  m
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();

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

    if (AsyncWraper.getTrustAllCertificates()) {
        try {
            //accepting all certificates because fuck this.
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            schemeRegistry.register(new Scheme("https", sf, 443));
            System.out.println("accepting all certificates");
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    }

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    clientHeaderMap = new HashMap<String, String>();

}

From source file:org.kegbot.app.service.CheckinService.java

private void doCheckin() {
    Log.d(TAG, "Performing checkin: " + CHECKIN_URL);
    final long now = System.currentTimeMillis();
    mPrefsHelper.setLastCheckinAttempt(now);

    final HttpClient client = new DefaultHttpClient();
    final HttpPost request = new HttpPost(CHECKIN_URL);
    final HttpParams requestParams = new BasicHttpParams();

    HttpProtocolParams.setUserAgent(requestParams, Utils.getUserAgent());
    request.setParams(requestParams);//ww w . j av a  2s  .  c  om

    try {
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("device_id", mDeviceId));
        params.add(new BasicNameValuePair("android_version", Build.VERSION.SDK));
        params.add(new BasicNameValuePair("android_device", Build.DEVICE));
        params.add(new BasicNameValuePair("app_package", getPackageName()));
        params.add(new BasicNameValuePair("app_version", String.valueOf(mKegbotVersion)));
        params.add(new BasicNameValuePair("app_date", BuildInfo.BUILD_DATE_HUMAN));
        params.add(new BasicNameValuePair("gcm_reg_id", mPrefsHelper.getGcmRegistrationId()));
        request.setEntity(new UrlEncodedFormEntity(params));

        final HttpResponse response = client.execute(request);
        Log.d(TAG, "Checkin complete");
        final String responseBody = EntityUtils.toString(response.getEntity());
        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode rootNode = mapper.readValue(responseBody, JsonNode.class);
        if (response.getStatusLine().getStatusCode() == 200) {
            mPrefsHelper.setLastCheckinSuccess(now);
            mPrefsHelper.setIsRegistered(true);
            processLastCheckinResponse(rootNode);
        }
    } catch (IOException e) {
        Log.d(TAG, "Checkin failed: " + e);
    }
}

From source file:org.graphity.core.util.jena.DatasetGraphAccessorHTTP.java

static private HttpParams createHttpParams() {
    HttpParams httpParams$ = new BasicHttpParams();
    // See DefaultHttpClient.createHttpParams
    HttpProtocolParams.setVersion(httpParams$, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams$, WebContent.charsetUTF8);
    HttpProtocolParams.setUseExpectContinue(httpParams$, true);
    HttpConnectionParams.setTcpNoDelay(httpParams$, true);
    HttpConnectionParams.setSocketBufferSize(httpParams$, 32 * 1024);
    HttpProtocolParams.setUserAgent(httpParams$, Jena.NAME + "/" + Jena.VERSION);
    return httpParams$;
}

From source file:mobi.dlys.android.core.net.http.client.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*w  w w .  j  a v a  2  s .co  m*/
 * 
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
public AsyncHttpClient()
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    KeyStore keyStroe = KeyStore.getInstance(KeyStore.getDefaultType());
    SSLSocketFactory ssf = new ClientSSLSocketFactory(keyStroe);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", ssf, 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    // threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    threadPool = ThreadPool.getInstance().getDefaultThreadPoolExecutor();

    // threadPool = new ThreadPoolExecutor(10, 30, 60, TimeUnit.SECONDS, new
    // LinkedBlockingQueue<Runnable>());

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}